1 / 7

第七章 文件

第七章 文件. 文件分类 打开/关闭文件 文件的读写 二进制文件. 文件分类. 文本文件 源程序 一般文字文件 二进制文件 图象文件 执行文件 Word、Excel、 数据库文件. 文件打开/关闭. 文件类型指针 # include <stdio.h> FILE *fp; 文件打开 写例: fp = fopen(“e:\test.txt”,”w”); 读例: fp = fopen(“e:\test.txt”,”r”); 文件关闭 例: fclose(fp);. 文件读写. 写到文件

Download Presentation

第七章 文件

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. 第七章 文件 文件分类 打开/关闭文件 文件的读写 二进制文件

  2. 文件分类 • 文本文件 • 源程序 • 一般文字文件 • 二进制文件 • 图象文件 • 执行文件 • Word、Excel、数据库文件

  3. 文件打开/关闭 • 文件类型指针 • #include <stdio.h> • FILE *fp; • 文件打开 • 写例:fp = fopen(“e:\\test.txt”,”w”); • 读例:fp = fopen(“e:\\test.txt”,”r”); • 文件关闭 • 例:fclose(fp);

  4. 文件读写 • 写到文件 • fprintf( fp, “格式控制”, [变量列表] ); • fputc( ch, fp ); • fputs( str, fp ); • 从文件读 • fscanf( fp, “格式控制”, 地址表列 ); • ch = fgetc(fp); • fgets( str, n, fp );

  5. 文件写 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); } }

  6. 文件读 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]); } }

  7. 二进制文件操作 • 打开二进制文件 • 写例: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

More Related