检查文件、目录是否存在,检查文件是否为空
1 检查文件是否存在
int checkDirFile(char* path) { struct stat fStatus; memset(&fStatus, 0, sizeof(fStatus)); int ret = stat(path, &fStatus); printf("retValue = %d\n", ret); if (0 != ret) { // file not exists printf("%s not exist\n", path); return -1; } printf("%s exist\n", path); return 0; }
2 检查文件是否为空
int checkFileNull(char* filePath) { FILE *fp = fopen(filePath, "r"); if (NULL == fp) { fprintf(stdout, "[%s]open file %s NG\n", __FUNCTION__, filePath); return -1; } /*判断文件是否为空*/ #if 1 if (EOF == fgetc(fp)) {/*读取一个字符,判断是否是结束符号*/ fprintf(stdout, "file1 [%s] is NULL \n", filePath); return -1; } fprintf(stdout, "file1 [%s] is not NULL \n", filePath); fseek(fp, 0, SEEK_SET); /*将文件指针指向开头*/ #else /*判别文件是否为空,若文件指针指向文件开头时,此方法判断失败*/ /*在读完文件的最后一个字符后,fp->flag仍然没有被置为_IOEOF,因而feof()仍然没有探测到文件结尾。 直到再次调用fgetc()执行读操作,feof()才能探测到文件结尾。这样就多执行了一次。 对于feof()这个函数, 它是先读再判断是否到文件尾, 也就是说在它之前一定要读一次才能做出判断。*/ /*以下方法在判断新打开文件时,不能正确判断不建议使用以下方法*/ if (EOF == feof(fp)) { fprintf(stdout, "file2 [%s] is NULL\n", filePath); return -1; } fprintf(stdout, "file2 [%s] is not NULL\n", filePath); #endif fclose(fp); return 0; }