阅读量:32
在 Linux 系统中,使用 C++ 进行文件的读写操作主要依赖于 库。下面是一个简单的示例,展示了如何使用 C++ 读取和写入文件。
写入文件
#include
#include
#include
int main() {
std::ofstream outFile("example.txt"); // 创建一个输出文件流对象,用于写入文件
if (!outFile) {
std::cerr << "无法打开文件进行写入" << std class="hljs-keyword">return 1;
}
outFile << "Hello, World!" << std class="hljs-comment">// 向文件中写入数据
outFile << "This is a test." << std class="hljs-built_in">close(); // 关闭文件
return 0;
}
读取文件
#include
#include
#include
int main() {
std::ifstream inFile("example.txt"); // 创建一个输入文件流对象,用于读取文件
if (!inFile) {
std::cerr << "无法打开文件进行读取" << std class="hljs-keyword">return 1;
}
std::string line;
while (std::getline(inFile, line)) { // 逐行读取文件内容
std::cout << line class="hljs-built_in">close(); // 关闭文件
return 0;
}
追加内容到文件
如果你想在现有文件的基础上追加内容,可以使用 std::ios::app 标志:
#include
#include
#include
int main() {
std::ofstream outFile("example.txt", std::ios::app); // 以追加模式打开文件
if (!outFile) {
std::cerr << "无法打开文件进行追加" << std class="hljs-keyword">return 1;
}
outFile << "This is an appended line." << std class="hljs-built_in">close(); // 关闭文件
return 0;
}
这些示例展示了如何在 Linux 系统中使用 C++ 进行基本的文件读写操作。你可以根据需要修改这些示例以满足你的需求。