【发布时间】:2016-09-27 11:00:12
【问题描述】:
我无法确定这一点 - 我的工作目录中有一个文件 input1.txt,但我不能 fopen() 它。
我的目录结构(Xcode):
main():
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;
}
我得到错误:
无法打开 input1.txt 进行阅读。没有这样的文件或目录
为什么这不起作用?文件肯定在那里...
【问题讨论】:
-
IDE 中的“当前”目录可能并不总是您认为的那样。检查项目设置以查看“当前”目录的设置。另外,请编辑您的问题,告诉我们您使用的是什么 IDE。你当然可以随时在程序中打印出来看看它是什么。
-
您必须解决的一件事是,检查
fopen()调用是否成功,这很好,但是您继续尝试读取它,这对您来说是不是不正确? -
提供完整路径并尝试打开文件或执行 system(pwd) 以获取工作目录。
-
我正在使用 Xcode - 打印工作目录说:
/Users/tomeldridge/Desktop/assignment6/build/Debug -
检查您的文件 input1.txt 是否被复制到 Debug 目录!如果没有,你已经找到了错误。