C++ 在 TXT 文件末尾追加数据
C++ 在 TXT 文件末尾追加数据
要在 TXT 文件末尾输出数据,可以使用文件流 (fstream) 打开文件,并将文件流的指针移动到文件末尾,然后使用文件流的输出运算符 (<<) 将数据输出到文件中。
以下是一个示例代码:
#include <fstream>
#include <iostream>
int main() {
// 打开文件流
std::ofstream file("example.txt", std::ios_base::app);
if (file.is_open()) {
// 将文件指针移动到文件末尾
file.seekp(0, std::ios_base::end);
// 输出数据到文件
file << 'Hello, world!' << std::endl;
// 关闭文件流
file.close();
} else {
std::cerr << "Failed to open file." << std::endl;
}
return 0;
}
在上面的示例中,我们将文件流的打开模式设置为 std::ios_base::app,这表示追加 (append) 模式,即在文件末尾添加数据而不是覆盖原有内容。然后使用 file.seekp(0, std::ios_base::end) 将文件指针移动到文件末尾。最后使用 file << 'Hello, world!' << std::endl; 将数据输出到文件中。注意,在输出数据后必须关闭文件流,以便保存数据并释放资源。
原文地址: https://www.cveoy.top/t/topic/ozk7 著作权归作者所有。请勿转载和采集!