2014-02-19 63 views
0

我是C初學者,對於如何執行此操作我有點困惑。我正在嘗試readdirstrcmp的功能,但它引發了很多錯誤。如何檢查文件夾中是否存在文件C

#include <stdio.h> 
#include <sys/types.h> 
#include <string.h> 
#include <dirent.h> 

int main(int argc, char *argv[]) 
{ 
    DIR *dirp; 
    struct dirent *direntp; 

    dirp = opendir(argv[1]); 
    if (dirp == NULL) 
    { 
     printf("File could not be open\n"); 

     return -1; 
    } 

    int i = 0; 
    while((direntp[i]=readdir(dirp)) != NULL) 
    { 
     if(strcmp(direntp[i], argv[2]) == 0) 
     { 
      printf("The file %d is in directory %s my friend!", argv[2], dirp); 
     } 

     i++; 
    } 

    closedir(dirp); 
    return 0; 
} 
+0

首先你必須谷歌你的問題,如果你得到任何錯誤,然後發佈您的代碼和錯誤列表在你的問題。 http://stackoverflow.com/q/230062/3184380 – Shell

+0

看看:[Similar Question](http://stackoverflow.com/questions/230062/whats-the-best-way-to-check-if -a-file-exists-in -c-cross-platform) – HvS

+0

另外,你的目錄內容迭代器很糟糕。在你的情況下,你還應該檢查'direntp [i]'是否實際上是一個文件'if(direntp [i] - > d_type == DT_REG){}'。正如我前一段時間所建議的[這裏](http://stackoverflow.com/a/17683417/1150918)。 – Kamiccolo

回答

0

嘗試打開讀模式類似這樣的文件,

FILE *f; 
f=fopen("file.txt","r"); 

if(f is not empty) 
    //file exits 
3
read about access 

if(access("myfile.txt", F_OK)) { 
    // file exists 
} 
+0

int access(const char * path,int amode)' - 因此第一個參數是整個文件路徑。 – HvS

0
int main(int argc, char *argv[]){ 
    DIR *dirp; 
    struct dirent *direntp; 

    dirp=opendir(argv[1]); 
    if (dirp == NULL){ 
     printf("File could not be open\n"); 
     return -1; 
    } 

    while((direntp=readdir(dirp)) != NULL){ 
     if(strcmp(direntp->d_name,argv[2]) == 0){ 
      printf("The file %s is in directory %s my friend!", argv[2], argv[1]); 
      break; 
     } 
    } 

    closedir(dirp); 
    return 0; 
} 
+0

它也可以識別目錄。作者所要求的實際上並非如此。 – Kamiccolo

相關問題