首先感謝鄧鄧同學問我文件的問題,然後又複習了一遍這知識,然後這裏把常見文件方法的彙集一下。
同時歡迎各位同學和我討論問題。
存儲數據的結構體
struct Student
{
int data;
int name;
char age[10];
};
一,C語言第一種方法,感覺最不好用的方法,太過於格式化,格式不能出一點錯誤
(這裏都只給出存儲和讀取部分代碼)
//將結構體數組存入文件中
FILE *fp;
fopen_s(&fp, "baocun.txt", "wt+"); //打開文件
for (int i = 0; i<N; i++) //將N條信息存儲進去
{
fprintf(fp, "%d %d %s\n", stuu[i].data, stuu[i].name,stuu[i].age);
}
fclose(fp); //關閉文件
//從文件中讀取數據
FILE *fpp;
fopen_s(&fpp, "baocun.txt", "r+"); //打開文件
int i=0; //將文件中數據讀取到結構體數組
while (!feof(fpp))
{
fscanf_s(fpp, "%d %d %s\n", &stu[i].data, &stu[i].name,stu[i].age,10);
i++;
}
fclose(fpp); //關閉文件
二,C語言第二種方法,二進制存儲
//將數據存入文件中
Student stu[N];
FILE *fp;
fopen_s(&fp, "baocun.txt", "wb");
fwrite(stu, sizeof(Student), N, fp); // 寫N條信息全部寫入文件
fclose(fp);
//將數據從文件中讀取出來
Student stuu[N];
FILE *fpp;
fopen_s(&fpp,"baocun.txt", "rb");
fread(stuu, sizeof(Student), N, fpp); // 將N條消息全部從文件中讀取出來
fclose(fpp);
三,C++中二進制存儲
//將數據存儲到文件
Student *stu;
ofstream outfile("11.txt", ios::out | ios::binary);
outfile.write((char*)stu, sizeof(Student));
outfile.close();
//文件數據重新讀入系統
ifstream infile("11.txt", ios::in | ios::binary);
int j=0;
while (infile.peek() != EOF)
{
infile.read((char*)stu, sizeof(food));
}
infile.close();