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; }