Answer the question
In order to leave comments, you need to log in
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;
}
Answer the question
In order to leave comments, you need to log in
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.
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.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question