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
爲什麼這個不行?該文件肯定是有...
IDE中的「當前」目錄可能並不總是您想象的那樣。檢查項目設置以查看「當前」目錄設置爲什麼。還請編輯您的問題,告訴我們您使用的是什麼IDE。你當然可以在程序裏面打印出來,看看它是什麼。 –
有一件事你必須解決,你檢查'fopen()'調用是否成功,這很好,但你繼續嘗試讀取它,這不看起來不正確嗎? –
提供完整路徑並嘗試打開文件或執行系統(pwd)以獲取工作目錄。 – SilentMonk