面向競賽程式設計的 C/C++、Java 和 Python 中的從外部檔案讀取/寫入


本文將介紹面向競賽程式設計的 C/C++、Java 和 Python 中的從外部檔案讀取/寫入。

Python 從檔案中讀取/寫入

在 Python 中,sys 模組用於從檔案獲取輸入並將輸出寫入檔案。我們透過程式碼來觀察如何實現。

示例

import sys
# For getting input
sys.stdin = open('sample.txt', 'r')
# Printing the Output
sys.stdout = open('sample.txt', 'w')

Java 從檔案中讀取/寫入

這裡我們藉助緩衝讀取器方法獲取與檔案讀取器關聯的輸入以從檔案中讀取輸入,藉助列印寫入器將資料列印迴文件。

示例

// Java program For handling 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++ 從檔案中讀取/寫入

這裡我們藉助 free open() 函式,並定義我們希望以什麼模式開啟檔案以及我們希望執行哪種操作。預設模式設定為只讀

示例

#include<stdio.h>
int main() {
   // For getting input
   freopen("sampleinp.txt", stdin);
   // Printing the Output
   freopen("sampleout.txt", "w", stdout);
   return 0;
}

結論

本文將介紹面向競賽程式設計的 C/C++、Java 和 Python 中的從外部檔案讀取/寫入。

更新於: 2019 年 8 月 29 日

355 次瀏覽

開啟你的 事業

完成課程獲得認證

開始
廣告
© . All rights reserved.