文件读写操作
注:下面仅是一个实例,没有实际意义,原则上就是用了,整体的思想,整片整片的读写。实际应用中,不太好。不建议用这种结构。
1: // FileOperation.cpp : 定义控制台应用程序的入口点。
2: //
3:
4: #include "stdafx.h"
5: #include <iostream>
6: #include <stdio.h>
7: #include <stdlib.h>
8: #define MaxSize 100
9: using namespace std;
10:
11:
12: typedef struct RaderInfor
13: {
14: char flag; //加 # 是为了保证数据正确,相当于一个校验的作用。
15: int dist[381];
16: } RaderInfor;
17: int main()
18: {
19: RaderInfor raderinfor[MaxSize]; //其实这也是初始化
20: //假如用指针的话,必须要用到new,这里没有用到指针。
21: memset(&raderinfor,0,sizeof(raderinfor)); //赋值为0
22: raderinfor[0].flag = '#';
23: for(int i = 0; i < 381; i++)
24: {
25: raderinfor[0].dist[i] = 9;
26: }
27: raderinfor[1].flag = '#';
28: for(int i = 0; i < 381; i++)
29: {
30: raderinfor[1].dist[i] = 8;
31: }
32: /********************写文件到data.txt*****************/
33: FILE *outfile = fopen("data.txt","wb");//表示二进制文件
34: fwrite(&raderinfor,sizeof(RaderInfor),MaxSize,outfile); //100表示最多可存放多少个这样的数据类型。 这里的数据类型表示结构体,切记。
35: fclose(outfile);
36:
37: /*******************读文件到屏幕中*****************/
38: FILE *infile = fopen("data.txt","rb");
39: //需要定义一个结构体去接收存放在文件流中的数据才行。
40: //void *fptemp = malloc(sizeof(RaderInfor)*MaxSize);
41: RaderInfor raderinfor2[MaxSize]; //其实这也是初始化
42: fread(&raderinfor2,sizeof(RaderInfor),MaxSize,infile);
43: for(int j = 0; j < MaxSize; j++)
44: {
45: cout << raderinfor2[j].flag << " ";
46: if(raderinfor2[j].flag == '#')
47: {
48: for(int i = 0; i < 381; i++)
49: {
50: cout << raderinfor[j].dist[i] << " ";
51: }
52: }
53: cout << endl;
54: }
55: return 0;
56: }
57:
下面在举一个文件读写例子,供大家参考:
1: #include <stdio.h>
2: #include <stdlib.h>
3:
4: typedef struct tagSTUDENTINFO{
5: int NO;
6: int Age;
7: // ...
8: } STUDENTINFO, *PSTUDENTINFO;
9:
10: void main()
11: {
12: int nStudent = 20;
13: PSTUDENTINFO pstruStudentInfo = (PSTUDENTINFO)malloc(sizeof(STUDENTINFO) * nStudent);
14:
15: pstruStudentInfo[0].NO = 1;
16: pstruStudentInfo[0].Age = 18;
17: pstruStudentInfo[1].NO = 2;
18: pstruStudentInfo[2].Age = 20;
19: // ...
20:
21: // write
22: FILE *outfile = fopen("data.txt", "wb");
23: fwrite(pstruStudentInfo, sizeof(STUDENTINFO), nStudent, outfile);
24: fclose(outfile);
25:
26: // read
27: FILE *infile = fopen("data.txt", "rb");
28: void *ptemp = malloc(sizeof(STUDENTINFO) * nStudent);
29: fread(ptemp, sizeof(STUDENTINFO), nStudent, infile);
30: printf("NO: %d Age: %d ", ((PSTUDENTINFO)ptemp)->NO, ((PSTUDENTINFO)ptemp)->Age);
31: fclose(infile);
32: }