每次修改嵌套的数据,编译,执行后会在txt文件用一行保存数据,每五次执行一次清空
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
struct game
{
int num;
int year;
float arr[3];
};
struct gj
{
int a;
game dz;
};
int count_lines(char *filename);
int main()
{
char filename[] = "g1.txt";
if(count_lines(filename)==5)
ofstream outfile("g1.txt", ios::trunc);
//结构体初始化
game g1;
gj gj1;
gj1.a = 100;
gj1.dz.num = 1;
gj1.dz.year = 2027;
gj1.dz.arr[0] = 1.1;
gj1.dz.arr[1] = 2.2;
gj1.dz.arr[2] = 3.3;
ofstream outfile("g1.txt", ios::app);
outfile <<gj1.dz.num << " "<< gj1.dz.year << " "<< gj1.dz.arr[0]<<" "<< gj1.dz.arr[1]<<" "<<gj1.dz.arr[2]<<endl;
cout<<gj1.dz.year<<endl;
outfile.close();
return 0;
}
int count_lines(char *filename) {
int n = 0;
ifstream ReadFile;
string tmp;
ReadFile.open(filename,ios::in);
if(ReadFile.fail())
{
return 0;
}
else
{
while (getline(ReadFile, tmp, '\n'))
{
n++;
}
ReadFile.close();
return n;
}
}