70 likes | 161 Views
第七章 文件. 文件分类 打开/关闭文件 文件的读写 二进制文件. 文件分类. 文本文件 源程序 一般文字文件 二进制文件 图象文件 执行文件 Word、Excel、 数据库文件. 文件打开/关闭. 文件类型指针 # include <stdio.h> FILE *fp; 文件打开 写例: fp = fopen(“e:\test.txt”,”w”); 读例: fp = fopen(“e:\test.txt”,”r”); 文件关闭 例: fclose(fp);. 文件读写. 写到文件
E N D
第七章 文件 文件分类 打开/关闭文件 文件的读写 二进制文件
文件分类 • 文本文件 • 源程序 • 一般文字文件 • 二进制文件 • 图象文件 • 执行文件 • Word、Excel、数据库文件
文件打开/关闭 • 文件类型指针 • #include <stdio.h> • FILE *fp; • 文件打开 • 写例:fp = fopen(“e:\\test.txt”,”w”); • 读例:fp = fopen(“e:\\test.txt”,”r”); • 文件关闭 • 例:fclose(fp);
文件读写 • 写到文件 • fprintf( fp, “格式控制”, [变量列表] ); • fputc( ch, fp ); • fputs( str, fp ); • 从文件读 • fscanf( fp, “格式控制”, 地址表列 ); • ch = fgetc(fp); • fgets( str, n, fp );
文件写 main() { int a[100], n, i; FILE *fp; scanf( “%d”, &n ); for ( i = 0; i < n; i++ ) scanf( “%d”, &a[i] ); fp = fopen( “test.txt”, “w” ); if ( fp != NULL ) { fprintf( fp,“%d\n”,n ); for (i=0;i<n;i++ ) fprintf( fp,“%d ”,a[i]); fclose(fp); } }
文件读 main() { int a[100], n, i; FILE *fp; fp = fopen( “test.txt”, “r” ); if ( fp != NULL ) { fscanf( fp, “%d”, &n ); for ( i = 0; i < n; i++ ) fscanf( fp, “%d”, &a[i] ); fclose(fp); printf(“%d\n”,n ); for (i=0;i<n;i++ ) printf(“%d ”,a[i]); } }
二进制文件操作 • 打开二进制文件 • 写例:fp = fopen(“e:\\test.dat”, “wb”); • 读例:fp = fopen(“e:\\test.dat”, “rb”); • 写二进制文件 • fwrite(void* buf,int size,int n,FILE* fp) • 读二进制文件 • fread(void* buf,int size,int n,FILE* fp) • 其它函数:fseek, ftell, rewind