Skip to content
Advertisement

Errors opening a file in c

currently I’m having problems with the function below trying to open a file, no matter what I give it the function can’t seem to open the file. I’m currently passing in “./input.txt” which is a file in the same directory as the executable. Is there anything blatantly wrong with the code that you guys can see?

FILE* openInputFile(char* inputFileName) 
{
    FILE* ifp= NULL;

    printf("%sn", inputFileName);
    ifp = fopen(inputFileName, "rb");

    if(ifp == NULL)
    {
        printf("Error opening input file.n");              
    }

    return ifp;
}

Advertisement

Answer

You are returning a pointer to memory stored on the stack. When the function exits the memory is freed and you are pointing to unallocated memory. You must pass the pointer in as a parameter to return the file name:

void openInputFile(char* inputFileName, FILE* ifp)
{
    FILE* ifp= NULL;

    printf("%sn", inputFileName);
    ifp = fopen(inputFileName, "rb");

    if(ifp == NULL)
    {
        printf("Error opening input file.n");              
    }
}
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement