学习目标:
用c++代码实现文件内数据的写入,和读取
学习内容:
主要用到了库来完成,其中ofstream实现读文件
ifstream实现写入。
代码
#include <fstream>
#include <iostream>
using namespace std;
int main()
{
char data[100];
// 以写模式打开文件
ofstream outfile;
outfile.open("afile.txt");
cout << "Writing to the file" << endl;
cout << "Enter your name: ";
cin.getline(data, 100);
// 向文件写入用户输入的数据
outfile << data << endl;
cout << "Enter your age: ";
cin >> data;
cin.ignore();
// 再次向文件写入用户输入的数据
outfile << data << endl;
// 关闭打开的文件
outfile.close();
// 以读模式打开文件
ifstream infile;
infile.open("afile.txt");
cout << "Reading from the file" << endl;
infile >> data;
// 在屏幕上写入数据
cout << data << endl;
// 再次从文件读取数据,并显示它
infile >> data;
cout << data << endl;
// 关闭打开的文件
infile.close();
return 0;
}
运行程序,可完成写数据,并把写入的数据读出来