文档详情

第8章 数据文件编程方法.ppt

发布:2017-06-04约8.44千字共38页下载文档
文本预览下载声明
第8章 数据文件编程方法 main(){ int i,j,t,x[10]={2,19,8,-10,7,0,89,3,13,50}; for(i=0;i9;i++) for(j=i+1;j10;j++) if(x[i]x[j]) t=x[i],x[i]=x[j],x[j]=t; for(i=0;i10;i++) printf(%d,,x[i]); getch(); } 改为将结果存入文件demo.txt中: #include stdio.h main(){ int i,j,t,x[10]={2,19,8,-10,7,0,89,3,13,50}; FILE *fp; fp=fopen(demo.txt,w); for(i=0;i9;i++) for(j=i+1;j10;j++) if(x[i]x[j]) t=x[i],x[i]=x[j],x[j]=t; for(i=0;i10;i++) fprintf(fp,%d,,x[i]); fclose(fp); } 还可以随时读入demo.txt文件内容,完成另外的操作. #include stdio.h main(){ int i,j,m,x[10]; FILE *fp; fp=fopen(demo.txt,r); for(i=0;i10;i++) fscanf(fp,%d,,x[i]); fclose(fp); m=x[0]; for(i=0;i10;i++) m=min(m,x[i]); printf(minimum=%d ,m); getch(); } int min(int x,int y){ return (xy?x:y); } 8.1 硬盘文件 8.1.1 二进制文件和文本文件 文件可以存放程序或数据; 文件是由文件名来识别的,只要指明文件名就可以读出或写入数据; 根据数据的组织形式,可以分为两种类型: 文本文件(也称ASCII文件): 二进制文件 两者的区别在于存储数值型数据的方式不同。 C语言把文件看作是一个字符(字节)的序列,即由一个一个字符(字节)的数据顺序组成,也就是所谓的流式文件。 8.1.2 缓冲文件系统 8.2 文件的打开与关闭 在C语言中,对文件的操作一般分为: 打开文件:利用一个文件指针使外部文件与程序之间建立数据交换的可能; 使用文件:使用该文件(读或写); 关闭文件:切断外部文件与程序之间的联系,并保证文件的完整性。 1.文件指针 在C语言的程序中是通过一个文件类型指针来使用外部文件。该结构体类型是系统定义的,包含在stdio.h中,取名为FILE。 对于每个要操作的文件,用户需先在程序中定义一个指向FILE类型的指针变量,如: FILE *fp; This pointer, called the file pointer, points to a structure that contains information about the file, such as the location of a buffer, the current character position in the buffer, whether the file is being read or written, and whether errors or end of file have occurred. Users dont need to know the details, because the definitions obtained from stdio.h include a structure declaration called FILE. 文件结构体类型定义: typedef struct{ short level; // fill/empty level of buffer unsigned flags; // file status flags char fd; // file descriptor unsigned char hold; // ungetc char if no buffer short bsize; // buffer size unsigned char buffer; // data transfer buffer unsigned char curp; // current active pointer unsigned istemp; // temporary
显示全部
相似文档