1. 当返回错误时,怎样判读是已经到达文件结尾,还是读错呢?
a. int feof(FILE *stream);
功能:判断是否已经到文件结束
参数:文件流
返回值:到文件结束,返回为非0,没有则返回0
b.int ferror(FILE *stream);
功能:判断是否读写错误
参数:文件流
返回值:是读写错误,返回为非0,不是则返回0
c.void clearerr(FILE *stream);
功能:清除流错误
参数:文件流
2. 通过检查fgetc的返回值,判断是文件尾还是出错
#include "stdio.h"
int main(int argc, char *argv[]){
FILE *fp;
int ret;
fp = open("./a.c","w+");
if(fp == NULL){
printf("open file a.c error
");
return -1;
}
printf("open file a.c success
");
fputc('a',fp);
rewind(fp);
ret = fgetc(fp);
printf("ret = %c
",ret);
ret = fgetc(fp);
printf("ret = %d
",ret);
printf("1feof=%d,ferror=%d
",feof(fp),ferror(fp));
clearerr(fp);
printf("2feof=%d,ferror=%d
",feof(fp),ferror(fp));
fclose(fp);
return 0;
}
3. 通过检查fgets的返回值,判断是文件尾还是出错
#include "stdio.h"
int main(int argc, char *argv[]){
FILE *fp;
char buf[] = "hello linux
";
char readbuf[128] = {0};
char *ret;
fp = open("./a.c","w+");
if(fp == NULL){
printf("open file a.c error
");
return -1;
}
printf("open file a.c success
");
fput(buf,fp);
rewind(fp);
fgets(readbuf,128,fp);
printf("1readbuf : %s
",readbuf);
memset(readbuf,128,0);
ret = fgets(readbuf,128,fp);
printf("2readbuf = %s,ret=%p
",readbuf,ret);
printf("feof=%d,ferror=%d
",feof(fp),ferror(fp));
fclose(fp);
return 0;
}
4. 例 cat 命令的实现
#include "stdio.h"
#include "unistd.h"
#include "fcntl.h"
#include "string.h"
int main(int argc, char *argv[]){
FILE *src_fp;
int read_ret;
if(argc < 2){
printf("please input src file
");
return -1;
}
src_fp = fopen(argv[1],"r");
if(src_fp == NULL){
printf("open src file %s error
",argv[1]);
return -2;
}
while(1){
read_ret = fgetc(src_fp);
if(feof(src_fp)){
printf("read file %s end
",argv[1]);
break;
}
fputc(read_ret,stdout);
}
fclose(src_fp);
return 0;
}