向文件写入
Coddy C++ 文件处理 课程的第 12 课,共 23 课。
现在,要执行文件写入,我们首先需要以输出模式打开文件,也就是说,需要使用 ofstream 类的对象来打开文件,而不是使用 ifstream 类的对象。
与从文件读取相比,向文件写入要容易得多。几乎每次我们都会使用 << 运算符。也有其他选择,例如:
.put(char):将指定的字符追加到文件中.write(string, length n):将指定字符串中的 n 个字符追加到文件中
不过,对于一般需求,<< 运算符就能胜任,因为我们可以写入任何想写的内容。
ofstream myfile;
myfile.open("example.txt");
if (myfile.is_open()) {
myfile << "Line 1" << endl;
myfile << "Line 2" << endl;
myfile << "Line 3" << endl;
}
myfile.close()Content of "example.txt":
Line 1
Line 2
Line 3挑战
简单标准输入中会提供一个
- 姓名(字符串)
- 年龄(int)
打开文件 output.txt,并写入消息 My name is {name} and I am {age} years old
*不要更改默认代码*
亲手试试
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
// 在这里输入你的代码
// 不要修改下面的代码!
ifstream file("output.txt");
string line;
while(!file.eof()){
getline(file, line);
cout << line;
}
file.close();
}C++ 文件处理中的所有课
自己练习: C++ 在线编译器