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