2016-05-29 63 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