第13章 文件输入\输出
13.1 与文件进行通信
13.1.1 文件是什么
C把文件看作是一系列连续的字节。C提供两种文件模式:文本模式和二进制模式。
13.1.2 文本模式和二进制模式
13.1.3 I/O的级别
13.1.4 标准文件
C程序会自动打开3个文件:标准输入,标准输出和标准错误输出。
13.2 标准I/O
/*count.c */ #define _CRT_SECURE_NO_WARNINGS #include<stdio.h> #include<stdlib.h> //提供exit()函数 int main(int argc, char* argv[]) { int ch; FILE *fp; //文件指针 unsigned long count = 0; if (argc != 2) { printf("Usage: %s filename\n", argv[0]); exit(EXIT_FAILURE); } if ((fp = fopen(argv[1], "r")) == NULL) { printf("Can't open %s\n", argv[1]); exit(EXIT_FAILURE); } while ((ch = getc(fp)) != EOF) { putc(ch, stdout); count++; } fclose(fp); printf("\nFile %s has %lu characters\n", argv[1], count); return 0; }
13.2.1 检查命令行参数
13.2.2 fopen()函数 程序使用fopen()函数打开文件,(函数声明在stdio.h)。
fopen()的第一个参数是待打开文件的名称,第2个参数是一个字符串,指定打开文件的模式(见f表open()的模式字符串)。
fopen()的返回值是一个文件指针(file pointer),文件指针的类型是指向FILE的指针(FILE定义在stdio.h中)
13.2.3 getc()和putc()函数
类似与getchar(),但getc()是从文件中获取一个字符。
ch = getc(fp); //fp是FILE类型的指针。
putc()是将字符放在指针指向的文件中:
putc(ch, fp);
13.2.4 文件结尾
如果getc()读取字符数发现它是文件结尾,它会返回一个值“EOF"。
13.2.5 fclose()函数
fclose(fp)函数关闭fp指定的文件。
成功关闭时返回0,否则返回EOF。借此可以检测文件是否成功关闭:
if (fclose(fp)!=0)
printf("Error in closeing file \n");
13.2.6 指向标准文件的指针
13.3 一个简单的文件压缩程序
(将某个文本文件的内容”压缩“,压缩方法是每3个字符只保留第一个,剩下两个丢弃)
//reducto.c #define _CRT_SECURE_NO_WARNINGS #include<stdio.h> #include<stdlib.h> #include<string.h> #define LEN 40 int main(int argc, char * argv[]) { FILE * in, *out; int ch; char name[LEN]; int count = 0; if (argc < 2) { fprintf(stderr, "Usage: %s filename\n", argv[0]); exit(EXIT_FAILURE); } //设置输入 if ((in = fopen(argv[1], "r")) == NULL) { fprintf(stderr, "I couldn't open the file \"%s\"\n ", argv[1]); exit(EXIT_FAILURE); } //设置输出 strncpy(name, argv[1], LEN - 5); // 拷贝文件名 name[LEN - 5] = '\0'; strcat(name, ".red"); if ((out = fopen(name, "w")) == NULL) { fprintf(stderr, "Can't create output file.\n"); exit(3); } //拷贝数据 while ( (ch=getc(in))!=EOF) { if (count++ % 3 == 0) putc(ch, out); } if (fclose(in) != 0 || fclose(out) != 0) fprintf(stderr, "Error in closing files.\n"); return 0; }
13.4 文件I/O:fprintf()、fscanf()、fgets()、fputs()
/*addaword.c --fprintf() fscanf() rewind()*/ #define _CRT_SECURE_NO_WARNINGS #include<stdio.h> #include<stdlib.h> #include<string.h> #define MAX 41 int main(void) { FILE *fp; char words[MAX]; if ((fp = fopen("wordy", "a+")) == NULL) { fprintf(stdout, "Can't open \"wordy\" file.\n"); exit(EXIT_FAILURE); } puts("Enter words to add to the file; press the #"); puts("key at the beginning of a line to terminate."); while ((fscanf(stdin, "%40s", words) == 1) && (words[0] != '#')) fprintf(fp, "%s\n", words); puts("File contents:"); rewind(fp);//回到文件开始处。 while (fscanf(fp, "%s", words) == 1) puts(words); puts("Done!"); if (fclose(fp) != 0) fprintf(stderr, "Error closing file\n"); return 0; }
13.4.1 fprintf()和fscanf()函数
13.4.2 fgets()和fputs()函数
13.5 随机访问:fseek()和ftell()
有了fseek()函数,便可把文件看作时数组,移动到文件的任意字节处。ftell()函数返回一个long类型的值,表示文件中的当前位置。