在Ubuntu中,C++處理文件輸入輸出主要使用iostream庫和fstream庫。iostream庫主要用于控制臺輸入輸出,而fstream庫則用于文件輸入輸出。
以下是一個簡單的示例,展示了如何在C++中使用fstream庫進行文件讀寫操作:
#include <iostream>
#include <fstream>
#include <string>
int main() {
// 創建一個文件輸出流對象,用于寫入文件
std::ofstream outFile("example.txt");
// 檢查文件是否成功打開
if (!outFile.is_open()) {
std::cerr << "Error: Unable to open file for writing." << std::endl;
return 1;
}
// 向文件中寫入數據
outFile << "Hello, World!" << std::endl;
outFile << "This is a simple example of file I/O in C++." << std::endl;
// 關閉文件
outFile.close();
// 創建一個文件輸入流對象,用于讀取文件
std::ifstream inFile("example.txt");
// 檢查文件是否成功打開
if (!inFile.is_open()) {
std::cerr << "Error: Unable to open file for reading." << std::endl;
return 1;
}
// 從文件中讀取數據并輸出到控制臺
std::string line;
while (std::getline(inFile, line)) {
std::cout << line << std::endl;
}
// 關閉文件
inFile.close();
return 0;
}
在這個示例中,我們首先包含了iostream和fstream庫。然后,我們創建了一個名為outFile
的文件輸出流對象,用于將數據寫入名為example.txt
的文件。接著,我們檢查文件是否成功打開,如果成功,則向文件中寫入兩行文本。之后,我們關閉文件。
接下來,我們創建了一個名為inFile
的文件輸入流對象,用于從example.txt
文件中讀取數據。同樣,我們檢查文件是否成功打開,如果成功,則逐行讀取文件內容并將其輸出到控制臺。最后,我們關閉文件。
要編譯這個程序,請在終端中輸入以下命令:
g++ -o file_io_example file_io_example.cpp
然后運行生成的可執行文件:
./file_io_example
這將創建一個名為example.txt
的文件,并將示例中的文本寫入該文件。接著,程序會讀取文件內容并將其輸出到控制臺。