1 所用函数
fgetc(FILE *fp):成功返回所读入的字符 失败为-1
fputc(int c,FILE *fp):第一个参数表示需要输出的字符 第二个参数表示输出的文件。成功返回输出的字符 失败返回-1
2 实现类似cp命令的复制程序,复制文件的同时输出该文件到屏幕 命令的格式copy src des(./a.out test1.txt test2)
3 实现
1 #include <stdio.h> 2 #include <errno.h> 3 #include <unistd.h> 4 #include <stdlib.h> 5 int main(int argc, char *argv[ ]) 6 { 7 FILE *fp1, *fp2; /* 源文件和目标文件 */ 8 int c; 9 if(argc != 3){ /* 检查参数个数 */ 10 printf("wrong command "); 11 exit(1); 12 } 13 if((fp1 = fopen(argv[1], "r")) == NULL){ /* 打开源文件 */ 14 perror("fail to open"); 15 exit(1); 16 } 17 if((fp2 = fopen(argv[2], "w+")) == NULL){ /* 打开目标文件 */ 18 perror("fail to open"); 19 exit(1); 20 } 21 /* 开始复制文件,每次读写一个字符 */ 22 while((c = fgetc(fp1)) != EOF){ /* 读源文件,直到将文件内容全部读完 */ 23 if(fputc(c, fp2) == EOF){ /* 将读入的字符写到目标文件中去 */ 24 perror("fail to write"); 25 exit(1); 26 } 27 if(fputc(c, stdout) == EOF){ /* 将读入的字符输出到屏幕 */ 28 perror("fail to write"); 29 exit(1); 30 } 31 } 32 if(errno != 0){ /* 如果errno变量不为0说明出错了 */ 33 perror("fail to read"); 34 exit(1); 35 } 36 fclose(fp1); /* 关闭源文件和目标文件 */ 37 fclose(fp2); 38 return 0; 39 }
4 截图