C语言实现成块读写文件
1、首先打开VC++6.0

2、选择文件,新建

3、选择C++ source file 新建一个空白文档

4、先声明头文件和主函数#include<stdio.h>main( ){
5、定义几个变量和文件指针还需要一个结构体,存放数据FIL苇质缵爨E *fp; int i; struct rec{ /*定义结构体类型*/ 艘早祓胂char id[10]; char name[15]; char department[15]; }record;

6、主要代码printf("涯箨唁峦***********************************************************\n"); printf("** Th足毂忍珩is program is to show the block file input & output**\n"); printf("***********************************************************\n"); if( (fp=fopen("d:\\infile.txt","w"))==NULL ) /*以文本只写方式打开文件*/ { printf("cannot open file"); exit(1); } printf("please input data:\n"); for( i=0;i<2;i++) { printf("Please input id:\n"); scanf("%s",record.id); /*从键盘输入*/ printf("Please input name:\n"); scanf("%s",record.name); printf("Please input department:\n"); scanf("%s",record.department); fwrite(&record,sizeof(record),1,fp); /* 成块写入文件*/ /*fprintf(fp,"%s %s %s\n",record.id,record.name,record.department); /* 写入文件*/ } fclose(fp); /*关闭文件*/ if((fp=fopen("d:\\infile.txt","r"))==NULL) { /*以文本只读方式重新打开文件*/ printf("cannot open file"); exit(0); } printf("output from file:\n"); for (i=0;i<2;i++) { fread(&record,sizeof(record),1,fp); /* 从文件成块读*/ printf("id:%s name:%s department:%s\n",record.id,record.name,record.department); /* 显示到屏幕*/ } /*从文件读入*/ /* while (fscanf(fp,"%s %s %s\n",record.id,record.name,record.department)!=EOF) { printf("id:%s name:%s department:%s\n",record.id,record.name,record.department); /* 显示到屏幕*/ /* }*/ fclose(fp); /*关闭文件*/ scanf("%d",i);}

7、运行结果
