C语言判断文件为空问题

Python019

C语言判断文件为空问题,第1张

在“C”文件读取操作时不能完全依赖于“while(!feof(FP)){...}”的判断。下面代码是改进后的代码,该代码执行后output文件内容和input文件内容一致,与使用“while(!feof(FP)){...}”相比,input文件的结尾符号(EOF)没有被读入到output文件中。

//main.c linux 下编译通过。

int main(void)

{

FILE *in, *out

char ch

if ((in = fopen("./input.txt", "r"))== NULL) //input.txt must exist in current directory.

{

fprintf(stderr, "Cannot open inputfile\n")

exit(0)

}

if((out=fopen("./output.txt","w"))==NULL)

{

fprintf(stderr,"Can not open the file.\n")

exit(0)

}

while(1)

{

ch=fgetc(in)

if(ch == -1)

break

fprintf(stdout,"The ASC of char %c is %d\n ",ch,ch)

fputc(ch,out)

}

fclose(in)

fclose(out)

return 0

}

我这里有一种方法,不知能满足楼主的要求不?

FILE *pfile

int filepos = 0

pfile = fopen("test.txt", "r")

fseek(pfile, 0, SEEK_END)

filepos = ftell(pfile)

if(0 == pos)

{

puts("The file is null!")

}

else

{

puts("The file has some content!")

}

只用C,有这几种方法:

1. 打开文件,获取长度,判断长度,长度为0,那文件肯定为空。可以用fseek(fp, 0L, SEEK_END )然后ftell读取位置,这个位置就是文件长度。

2. 打开文件,读取文件,如果读取的长度为0,文件也一定为空

3. 用stat()函数来获取文件状态,判断里面的st_size就可以了,这个函数的用法,你可以百度一下