2017-09-15 125 views
-2

我有一些問題的fopen()函數C.fopen()函數返回「沒有這樣的文件或目錄」

我'解析目錄,並把所有的路徑字符數組(字符**)。之後,我應該打開所有這些文件。並且... fopen對於某些文件返回「沒有這樣的文件或目錄」。我真的不明白,爲什麼。

  1. 所有的路徑都是正確的。我檢查了它。
  2. 我有 打開這些文件的所有權限。
  3. 如果我從錯誤日誌中複製路徑到文件,並嘗試使用 通過我的程序打開這個文件 - 它的工作原理。
  4. 其他 程序不能使用這些文件(我認爲)。

我能做什麼錯?

int main(int argc, char *argv[]){ 
    char** set = malloc(10000*sizeof(char*)); 
    char* path = argv[1]; 
    listdir(path, set); /* Just parse directory. Paths from the root. No problem in this function. all paths in the variable "set" are right */ 
    int i=0; 
    while(i<files){ /* files is number of paths */ 
     FILE* file = fopen(set[i++],"rb"); 
     fseek(file, 0L, SEEK_END); 
     int fileSize = ftell(file); 
     rewind(file); 
     /*reading bytes from file to some buffer and close current file */ 
     i++; 
    } 
} 
+2

你做錯了什麼是你沒有提供[mcve] –

+2

請顯示你的代碼。 –

+1

調試器。打破fopen()。逐字節檢查set []數組。如果這很尷尬,請將數組元素strcpy()轉換爲本地char數組(例如filepath [256]),然後檢查它。找出路徑不正確的原因並解決它。 –

回答

1
  1. 你增加 '我' 兩次。可能是錯誤的?
  2. 您可以使用stat()打開文件大小。
  3. ftell()返回「long」,不要將它轉換爲「int」,因爲它可以縮短,並且你失去正確的值。

試試這個代碼:

#include <stdio.h> 
#include <sys/stat.h> 

/* example of listdir, replace it with your real one */ 
int listdir(const char *path, char *set[]) 
{ 
    set[0] = "0.txt"; 
    set[1] = "1.txt"; 
    set[2] = "2.txt"; 
    set[3] = "3.txt"; 
    set[4] = "4.txt"; 

    return 5; 
} 

int main(int argc, char *argv[]) { 
    int files; 
    char *path = argv[1]; 
    char **set = malloc(1000 * sizeof(char *)); 

    files = listdir(path, set); 

    for (int i = 0; i < files; i++) { 
     struct stat st; 
     stat(set[i], &st); 
     printf("FileSize of %s is %zu\n", set[i], st.st_size); 
    } 
    free(set); 
} 
+0

*不要試圖使用char **作爲char * name []不兼容。*?!?!?!?請解釋一下。 –

+0

安德魯,請忽略那句話,這是愚蠢的想法:) – MrCryo

0

(我猜你一定Posix的系統上,Linux的希望)

可能是你listdir是錯誤的。 FWIW,如果您在其中使用readdir(3),則需要連接目錄名稱和文件名(中間有/,可能使用snprintf(3)asprintf(3)用於此目的)。

但可以肯定,

FILE* file = fopen(set[i++],"rb"); ////WRONG 

是錯上加錯。首先,你增加了兩次i++(這裏還爲時過早)。然後,你應該閱讀fopen(3)和處理失敗的情況下,至少有:

char* curpath = set[i]; 
    assert (curpath != NULL); 
    FILE* file = fopen(curpath, "rb"); 
    if (!file) { perror(curpath); exit(EXIT_FAILURE); }; 

測試fopen對失敗是強制的結果。請注意,我將通過相同的curpathperror(3)失敗。

您可能還想檢查一下您目前的working directory是否符合您的預期。爲此,請使用getcwd(2)

也使用strace(1)(在Linux上)瞭解您的程序完成了哪些system calls

相關問題