Search code examples
cfopen

fopen() returns NULL, file exists in current directory


I can't make head or tail of this - I have a file input1.txt in my working directory, but I can't fopen() it.

My directory structure (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;
}

I get the error:

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

Why does this not work? The file definitely is there...


Solution

  • In Xcode, your project "folders" are better referred to as "groups," that may or may not refer to actual folders on the disk. The group directory hierarchy is stored in your project settings and does not necessarily correspond to your filesystem hierarchy (think symlinks). Try right-clicking on one of the files in question, and selecting "Show in Finder" to see its real location on disk.

    If the input1.txt isn't actually in the same directory on disk as the calling function file, try moving it through Finder, and re-adding it to the project through Xcode (File-> "Add files to...").

    Edit: I just found a tool to synchronize your group and file structures. Take a look at synx