在Linux中,C++可以使用标准库中的iostream和fstream来进行文件I/O操作。iostream用于控制台输入输出,而fstream则用于文件输入输出。
以下是一些基本的文件I/O操作:
使用fstream的open()函数打开一个文件。例如:
#include <fstream>
std::fstream file;
file.open("example.txt", std::ios::in | std::ios::out);
这里,我们打开了一个名为example.txt的文件,并指定了读写模式。
使用fstream的close()函数关闭一个文件。例如:
file.close();
使用iostream的>>运算符或者getline()函数来读取文件。例如:
std::string line;
while (std::getline(file, line)) {
std::cout << line << std::endl;
}
这里,我们使用getline()函数逐行读取文件,并将每一行输出到控制台。
使用iostream的<<运算符或者write()函数来写入文件。例如:
file << "Hello, world!" << std::endl;
这里,我们将字符串"Hello, world!"写入到文件中。
使用fstream的is_open()函数来检查文件是否成功打开。例如:
if (file.is_open()) {
// 文件成功打开
} else {
// 文件打开失败
}
使用stat()函数来获取文件的大小。例如:
struct stat st;
stat("example.txt", &st);
int size = st.st_size;
这里,我们使用stat()函数获取了example.txt文件的大小,并将其存储在变量size中。
以上是一些基本的文件I/O操作,当然还有其他的操作,比如文件的复制、删除等等。