A
A
Artyom_Kopan2021-09-29 21:57:27
C++ / C#
Artyom_Kopan, 2021-09-29 21:57:27

How to solve the problem with opening a text file in C?

I have the following piece of code:

FILE* openInputFile()
{
    printf("Enter the name of the input file: ");
    char inputFileName[PATH_MAX + 1];
    scanf("%s", inputFileName);
    if (strstr(inputFileName, ".txt") == NULL)
        strcat(inputFileName, ".txt");
    FILE* inputFile = fopen(inputFileName, "r");
    return inputFile;
}

int main()
{
    FILE* inputFile = openInputFile();
    if (inputFile == NULL) {
        printf("File open error!");
        return 0;
    }
    ...
    return 0;
}

This code, when trying to open a file, throws "File open error!", that is, the openInputFile function returns NULL.
Why is this happening and what can be done about it?

Answer the question

In order to leave comments, you need to log in

4 answer(s)
W
Wataru, 2021-09-29
@wataru

The code looks correct. See in the project properties which directory is the current directory for the program. Maybe this is not a folder with a project, but a folder where the assembled executable is located. Try putting the file in there.
Try to shove the file to the root of the disk and enter the absolute path to it.

R
res2001, 2021-09-30
@res2001

Because almost all functions can return an error in one way or another.
When fopen returns NULL, it is a signal that an error occurred while executing the function. You must parse the value of errno and display a meaningful message to the user.
https://en.cppreference.com/w/c/io/fopen
Now you have a single message for all errors. You can simply call the strerror function with the error code errno to get a normal up-to-date error message.
https://en.cppreference.com/w/c/string/byte/strerror
Yes. Enter the full path to the file, then you will not have errors associated with the absence of the file where the program tries to find it. But this does not negate the correct error handling in the program.

T
Tony, 2021-09-29
@AntonSazonov

Display what you have in inputFileNamebefore calling fopen.

C
CityCat4, 2021-09-30
@CityCat4

After opening the file, you need to check the status of the error and display a meaningful message about it.
man perror()
man strerror()
man errno()

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question