My goal is to gather input and open files based on that input.
FILE*
open_input_file (char* fileName) //opens source file to be read
{
return fopen(fileName, "r");
}
In an earlier function, I collect input from the user and save it to fileName. When I debug the program, it tells me fopen is returning NULL. That’s not what I want, and I’m not sure where the problem is.
int main(void)
{ FILE* inFile = NULL;
char infileName[32] = {'\0'};
gather_input(infileName); // infileName is an output parameter for this
inFile = open_input_file(infileName);
}
I don’t know what the problem is. Any thoughts?
If
fopenreturnsNULL, the open failed.errnowill hold the failure code andstrerror(errno)will return a short description of why the open failed.Off-topic
gather_inputbetter make sureinfileNameis null-terminated to prevent buffer overflows. The simplest way to do this is to define the size of the file name buffer as a macro and set the last character to 0.This isn’t very flexible. You could instead pass the size of the file name buffer into
gather_input.An alternative to setting the last character, if using standard string manipulation functions, is to use the
strl*functions (strlcpyandstrlcat) rather than their unbounded cousins. If you aren’t usingstrl*, you should be usingstrncpyandstrncat.