在 Linux 中,C++ 可以使用標準庫中的 <fstream>
來進行文件操作。<fstream>
提供了 ifstream
(用于讀取文件)、ofstream
(用于寫入文件)和 fstream
(用于讀寫文件)這三個類。
以下是一些基本的文件操作示例:
#include <iostream>
#include <fstream>
int main() {
std::ifstream inputFile("input.txt"); // 打開名為 input.txt 的文件進行讀取
std::ofstream outputFile("output.txt"); // 打開名為 output.txt 的文件進行寫入
std::fstream file("file.txt", std::ios::in | std::ios::out); // 打開名為 file.txt 的文件進行讀寫
if (!inputFile.is_open()) {
std::cerr << "無法打開輸入文件" << std::endl;
return 1;
}
if (!outputFile.is_open()) {
std::cerr << "無法打開輸出文件" << std::endl;
return 1;
}
if (!file.is_open()) {
std::cerr << "無法打開文件進行讀寫" << std::endl;
return 1;
}
// ... 進行文件操作 ...
inputFile.close(); // 關閉輸入文件
outputFile.close(); // 關閉輸出文件
file.close(); // 關閉文件
return 0;
}
std::string line;
while (std::getline(inputFile, line)) {
std::cout << line << std::endl;
}
outputFile << "Hello, World!" << std::endl;
outputFile << "Appended text" << std::endl;
if (inputFile.eof()) {
std::cout << "已到達文件末尾" << std::endl;
}
inputFile.close();
outputFile.close();
file.close();
這些示例展示了如何在 Linux 中使用 C++ 進行基本的文件操作。你可以根據需要修改這些示例以滿足你的需求。