Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Đầu vào/Đầu ra từ file ngoài trong C/C++, Java và Python cho Lập trình thi đấu

Trong bài viết này, chúng ta sẽ tìm hiểu về Đầu vào/Đầu ra từ file ngoài trong C/C++, Java và Python cho Lập trình thi đấu (Competitive Programming).

Python I/O từ file

Trong Python, module sys được dùng để lấy input từ file và ghi output ra file. Hãy xem triển khai dưới dạng code.

Ví dụ

import sys
# Để lấy input
sys.stdin = open('sample.txt', 'r')
# In Output
sys.stdout = open('sample.txt', 'w')

Java I/O từ file

Ở đây chúng ta nhờ phương thức buffered reader để lấy input kết hợp với file reader để đọc input từ file và print writer để in dữ liệu ngược lại file.

Ví dụ

// Chương trình Java xử lý Input/Output
import java.io.*;
class Input {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new
        FileReader("sampleinp.txt"));
        PrintWriter pw = new PrintWriter(new
        BufferedWriter(new
        FileWriter("sampleout.txt")));
        pw.flush();
    }
}

C/C++ I/O từ file

Ở đây chúng ta nhờ hàm freopen() miễn phí và định nghĩa chế độ mở file và loại thao tác muốn thực hiện. Mặc định chế độ là chỉ đọc.

Ví dụ

#include 
int main() {
    // Để lấy input
    freopen("sampleinp.txt", "r", stdin);
    // In Output
    freopen("sampleout.txt", "w", stdout);
    return 0;
}

Kết luận

Trong hướng dẫn này, chúng ta sẽ tìm hiểu về Đầu vào/Đầu ra từ file ngoài trong C/C++, Java và Python cho Lập trình thi đấu.