c++ 利用fsteam 写txt文件
时间: 2024-03-22 17:38:08 浏览: 20
您好,以下是 C++ 利用 fstream 写入 txt 文件的示例代码:
```cpp
#include <iostream>
#include <fstream>
#include <string>
int main()
{
std::string filename = "example.txt"; // 文件名
std::string content = "Hello, world!"; // 写入内容
// 使用 ofstream 类以写入模式打开文件
std::ofstream outfile(filename, std::ios::out);
if (!outfile.is_open()) // 判断文件是否成功打开
{
std::cerr << "Failed to open file: " << filename << std::endl;
return -1;
}
// 将内容写入文件
outfile << content;
// 关闭文件
outfile.close();
std::cout << "File written successfully!" << std::endl;
return 0;
}
```
上述代码中,我们使用 `ofstream` 类以写入模式打开文件,并判断文件是否成功打开。然后,我们将内容写入文件,最后关闭文件。运行程序后,会在程序所在目录下创建名为 `example.txt` 的文件,并将内容写入其中。
需要注意的是,如果文件不存在,则会自动创建该文件;如果文件已经存在,且以写入模式打开,则会清空文件中的所有内容,重新写入新的内容。如果想要在文件末尾追加内容而不是清空文件,可以使用 `std::ios::app` 模式打开文件。