在Linux下,C++可以使用標準庫中的iostream和fstream來進行文件I/O操作。iostream主要用于控制臺輸入輸出,而fstream則用于文件輸入輸出。
下面是一些基本的文件I/O操作示例:
#include <fstream>
std::ifstream infile("file.txt"); // 打開一個名為file.txt的文件用于讀取
std::ofstream outfile("output.txt"); // 打開一個名為output.txt的文件用于寫入
infile.close(); // 關閉文件
outfile.close();
std::string line;
while (std::getline(infile, line)) {
std::cout << line << std::endl; // 輸出每一行
}
outfile << "Hello, World!" << std::endl; // 寫入一行文本
outfile.open("output.txt", std::ios::app); // 打開文件用于追加
outfile << "New line" << std::endl;
outfile.close();
注意:在使用fstream進行文件I/O時,需要包含頭文件
以上是基本的文件I/O操作,實際上還有很多其他的操作,比如獲取文件大小、定位文件指針等。如果需要更詳細的介紹,可以參考C++標準庫的文檔或者相關的書籍。