For my assignment I have to create a program similar to the -wc unix command which counts words, lines, etc.
I have to read in flags and read in a text file.
I’ve set up all the flags and now I’m trying to read in a text file. I don’t think I’m doing this right.
void readInFile(char** argv, int arg)
{
FILE *myFile;
char c;
myFile = fopen(argv[arg], "r");
if(!myfile)
{
printf("%s not found!", argv[arg]);
exit(EXIT_FAILURE);
}
}
in my main I call the function readInFile() and pass 2 arguments. Argv and the element where the file should be. So assume this to be correct.
I need help with actually opening up the file. I feel like my fopen() is wrong. I’m new to reading/writing files in C. Thanks alot!
I’m going to give you some general advice here.
Usually functions should do a single job. In this case, you are writing a function to read in a single file. So, don’t pass a pointer to all the command-line arguments; pass in a single read-only pointer to the name of the file to open. Then in
main()select the correct argument and pass that as the argument.Now, if this function will be reading in the file and doing nothing else, it needs to return the data somehow. But if this function will be doing the equivalent of
wc, maybe it will read the file and print stuff, not return any data to themain()function. Then maybe the name should be improved:The actual call to
fopen()looks fine to me.You check for error, and then call
exit()immediately. That’s one way to do it. Another way to do it is to return an error code from your function, and have the caller (themain()function) check for failure, and handle the error there.For a program this simple, it doesn’t matter much. But once you start building larger systems in software, you will be happier if your functions work well together, and part of that is making functions that return error codes rather than terminating your whole program on any error.
Why am I using
0for the success code, and non-zero for failure? It’s a common way to do it. It’s easy to test for non-zero, likeif (result)and there are many non-zero codes but only one zero, so you can return many different kinds of errors, but there is only one value needed for “success”.Note that instead of calling
exit()frommain(), you can just use thereturnstatement. When you return0frommain(), that signals success, and a non-zero value indicates an error. So you could just usereturn result;frommain()if you like.In my dummy code, I’m just returning
1as the error code. But actually, when you callfopen()it returns an error code to you, in a global variable callederrno. Probably a better option is to make your function return the actual error code as specified inerrno. You could even modify the print statement in themain()function print theerrnocode, or use thestrerror()function to turn that error code into a human-readable message.