2016-05-29 65 views
0

我無法制作頭部或尾部 - 我在我的工作目錄中有一個文件input1.txt,但我不能fopen()它。fopen()返回NULL,文件存在於當前目錄

我的目錄結構(Xcode中):

主():

const char* fileName = "input1.txt"; 
if (argc > 1) 
{ 
    fileName = argv[1]; 
} 
printf("Opening file: %s\n", fileName); 

clock_t timer = clock(); 

HashMap* map = hashMapNew(10); 

// --- Concordance code begins here --- 
// Be sure to free the word after you are done with it here. 
FILE *in; 
if ((in = fopen(fileName, "r")) == NULL) { 
    printf ("Can’t open %s for reading. %s\n", fileName, strerror(errno)); 
} 
char* w = nextWord(in); 
printf("%s",w); 

nextWord():

char* nextWord(FILE* file) 
{ 
    int maxLength = 16; 
    int length = 0; 
    char* word = malloc(sizeof(char) * maxLength); 
    while (1) 
    { 
     char c = fgetc(file); 
     if ((c >= '0' && c <= '9') || 
      (c >= 'A' && c <= 'Z') || 
      (c >= 'a' && c <= 'z') || 
      c == '\'') 
     { 
      if (length + 1 >= maxLength) 
      { 
       maxLength *= 2; 
       word = realloc(word, maxLength); 
      } 
      word[length] = c; 
      length++; 
     } 
     else if (length > 0 || c == EOF) 
     { 
      break; 
     } 
    } 
    if (length == 0) 
    { 
     free(word); 
     return NULL; 
    } 
    word[length] = '\0'; 
    return word; 
} 

我得到的錯誤:

Can’t open input1.txt for reading. No such file or directory

爲什麼這個不行?該文件肯定是有...

+3

IDE中的「當前」目錄可能並不總是您想象的那樣。檢查項目設置以查看「當前」目錄設置爲什麼。還請編輯您的問題,告訴我們您使用的是什麼IDE。你當然可以在程序裏面打印出來,看看它是什麼。 –

+0

有一件事你必須解決,你檢查'fopen()'調用是否成功,這很好,但你繼續嘗試讀取它,這不看起來不正確嗎? –

+0

提供完整路徑並嘗試打開文件或執行系統(pwd)以獲取工作目錄。 – SilentMonk

回答

0

在Xcode中,您的項目「文件夾」最好稱爲「組」,可能或不可能引用磁盤上的實際文件夾。組目錄層次結構存儲在您的項目設置中,不一定對應於您的文件系統層次結構(請考慮符號鏈接)。嘗試右鍵單擊其中一個有問題的文件,然後選擇「在Finder中顯示」以查看其在磁盤上的真實位置。

如果input1.txt實際上與調用函數文件不在同一個磁盤目錄中,請嘗試通過Finder移動它,然後通過Xcode(File->「Add files to」)重新添加到項目中。 ..「)。

編輯:我剛找到一個工具來同步你的組和文件結構。 Take a look at synx