一、ofstream、ifstream
1、代码
#include "stdafx.h"
#include<fstream>
#include<iostream>
#include<string>
using namespace std;
struct TYPE
{
int id;
char name[10];
int buff[10];
};
int main()
{
cout << "write 10 times" << endl;
ofstream out("1.txt",ios::app);
if (!out)
{
cout << "open file err" << endl;
return -1;
}
for (int num = 0; num < 10; num++)
{
TYPE v;
v.id = num;
strcpy(v.name, "kira");
for (int i = 0; i < 10; i++)
{
v.buff[i] = i;
}
out << v.id << " ";
out << v.name << " ";
for (int i = 0; i < 9; i++)
{
out << v.buff[i] << " ";
}
out << v.buff[9] << '\n';
cout << v.id << " ";
cout << v.name << " ";
for (int i = 0; i < 10; i++)
{
cout << v.buff[i] << " ";
}
cout << endl;
}
out.close();
cout << "read from txt" << endl;
ifstream in("1.txt");
if (!in)
{
cout << "open file err" << endl;
return -1;
}
TYPE vv;
while (in >> vv.id)
{
in >> vv.name;
for (int i = 0; i < 10; i++)
{
in >> vv.buff[i];
}
cout << vv.id << " ";
cout << vv.name << " ";
for (int i = 0; i < 10; i++)
{
cout << vv.buff[i] << " ";
}
cout << endl;
}
return 0;
}
2、结果
2.1 生成文件如下
2.2 屏幕显示如下