温馨提示×

Linux里C++文件怎么读写

小樊
33
2025-11-09 08:38:44
栏目: 编程语言

在 Linux 系统中,使用 C++ 进行文件的读写操作主要依赖于 <fstream> 库。下面是一个简单的示例,展示了如何使用 C++ 读取和写入文件。

写入文件

#include <iostream> #include <fstream> #include <string> int main() { std::ofstream outFile("example.txt"); // 创建一个输出文件流对象,用于写入文件 if (!outFile) { std::cerr << "无法打开文件进行写入" << std::endl; return 1; } outFile << "Hello, World!" << std::endl; // 向文件中写入数据 outFile << "This is a test." << std::endl; outFile.close(); // 关闭文件 return 0; } 

读取文件

#include <iostream> #include <fstream> #include <string> int main() { std::ifstream inFile("example.txt"); // 创建一个输入文件流对象,用于读取文件 if (!inFile) { std::cerr << "无法打开文件进行读取" << std::endl; return 1; } std::string line; while (std::getline(inFile, line)) { // 逐行读取文件内容 std::cout << line << std::endl; } inFile.close(); // 关闭文件 return 0; } 

追加内容到文件

如果你想在现有文件的基础上追加内容,可以使用 std::ios::app 标志:

#include <iostream> #include <fstream> #include <string> int main() { std::ofstream outFile("example.txt", std::ios::app); // 以追加模式打开文件 if (!outFile) { std::cerr << "无法打开文件进行追加" << std::endl; return 1; } outFile << "This is an appended line." << std::endl; outFile.close(); // 关闭文件 return 0; } 

这些示例展示了如何在 Linux 系统中使用 C++ 进行基本的文件读写操作。你可以根据需要修改这些示例以满足你的需求。

0