c++ 写入txt文件
时间: 2023-10-18 20:06:30 浏览: 48
你可以使用 C++ 的标准库中的 `fstream` 类来写入文本文件。下面是一个示例代码:
```c++
#include <iostream>
#include <fstream>
int main() {
std::ofstream outfile; // 创建文件输出流对象
outfile.open("example.txt"); // 打开文件,如果文件不存在则创建新文件
if (outfile.is_open()) { // 检查文件是否打开成功
outfile << "Hello, world!" << std::endl; // 向文件写入数据
outfile.close(); // 关闭文件
std::cout << "Data written to file successfully." << std::endl;
} else {
std::cerr << "Error: Unable to open file." << std::endl;
}
return 0;
}
```
上面的代码会向名为 `example.txt` 的文本文件写入一行字符串。如果文件不存在,则会自动创建新文件。如果文件打开成功,则会在控制台输出一条成功写入数据的消息。如果文件打开失败,则会在控制台输出错误信息。
你可以根据需要修改文件名和要写入的数据。同时,你也可以使用 `fstream` 类的其他方法来读取和操作文本文件。
相关问题
c++ 读写txt文件
读取txt文件:
```cpp
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
ifstream inputFile("input.txt"); // 打开文件
string line;
if (inputFile.is_open()) { // 判断文件是否成功打开
while (getline(inputFile, line)) { // 逐行读取
cout << line << endl; // 输出每行文本
}
inputFile.close(); // 关闭文件
} else {
cout << "Unable to open file" << endl;
}
return 0;
}
```
写入txt文件:
```cpp
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ofstream outputFile("output.txt"); // 打开文件
if (outputFile.is_open()) { // 判断文件是否成功打开
outputFile << "Hello World!" << endl; // 写入文本
outputFile.close(); // 关闭文件
} else {
cout << "Unable to open file" << endl;
}
return 0;
}
```
注意:读取和写入文件时,需要使用文件流对象来操作文件,并且需要进行文件是否成功打开的判断。
c++追加写入txt文件
你可以使用标准库中的ofstream类来实现向txt文件中追加写入内容。具体操作如下:
1. 打开文件并将文件指针定位到文件末尾;
2. 使用ofstream类的<<操作符将要写入的内容插入到文件中;
3. 关闭文件。
下面是一个简单的例子:
```c++
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
// 打开文件并将文件指针定位到文件末尾
ofstream outfile("test.txt", ios::out | ios::app);
if (!outfile)
{
cout << "打开文件失败!" << endl;
return 1;
}
// 写入内容
outfile << "Hello, World!" << endl;
// 关闭文件
outfile.close();
return 0;
}
```
在上面的例子中,ofstream类的构造函数中使用了ios::out | ios::app参数,其中ios::out表示以写入模式打开文件,ios::app表示在文件末尾追加写入内容。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)