高铁1301次列车时刻表:在文件操作中,能否将文字和数据同是存入数组中?如何将文字和数据同是存入数据文件中?

来源:百度文库 编辑:神马品牌网 时间:2024/04/29 03:44:24
在文件操作中,能否将文字和数据同是存入数组中?如何将文字和数据同是存入数据文件中?
比如:
小明 60
小刚 80
小红 100
怎么进行写入操作?
能否给出一个完整的操作程序?

// zd_17.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <windows.h>
#define N 3

struct tagIndexTable{
char name[10];
int point;
};
typedef struct tagIndexTable NAME_POINT;

int main(int argc, char* argv[])
{
NAME_POINT date[N];
for(int i=0;i<N;i++)
{
printf("input date%d:\n",i+1);
scanf("%s%d",&date[i].name,&date[i].point);
}
for(i=0;i<N;i++)
{
printf("date%d:\n",i+1);
printf("%s %d\n",date[i].name,date[i].point);
}
//存入文件中
HANDLE hFile;
DWORD size;
hFile=CreateFile("date.txt",GENERIC_WRITE,0,NULL,CREATE_ALWAYS,FILE_ATTRIBUTE_HIDDEN,NULL);
if (hFile==INVALID_HANDLE_VALUE)
{
printf("open file fail\n");
return 0;
}
for(i=0;i<N;i++)
{
WriteFile(hFile,&date[i],sizeof(NAME_POINT),&size,NULL);
}
CloseHandle(hFile);
//取文件
NAME_POINT date_load[N];
hFile=CreateFile("date.txt",GENERIC_READ,0,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,NULL);
if (hFile==INVALID_HANDLE_VALUE)
{
printf("open file fail\n");
return 0;
}
for(i=0;i<N;i++)
{
ReadFile(hFile,&date_load[i],sizeof(NAME_POINT),&size,NULL);
}
CloseHandle(hFile);

for(i=0;i<N;i++)
{
printf("loaded date%d:\n",i+1);
printf("%s %d\n",date_load[i].name,date_load[i].point);
}
printf("Hello World!\n");
return 0;
}

输出:
input date1:
小明 60
input date2:
小刚 80
input date3:
小红 100
date1:
小明 60
date2:
小刚 80
date3:
小红 100
loaded date1:
小明 60
loaded date2:
小刚 80
loaded date3:
小红 100
Hello World!
Press any key to continue