在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++标准库的文档或者相关的书籍。