I've assumed you need the file path to be accepted as an input to the program.
If so then it depends on how you would like to pass this information to the program, but I'm not convinced that passing command line arguments could be considered an runtime input from user. However you could pass a path to the file as an command line argument, and access it using argc
and argv
arguments of the main
function :
int main(int argc, char *argv[])
{
//argv[0] is always name of the program
//argv[1] is the first command line argument
//and so on up to argc-1 (argv[argc-1] is the last argument)
//so, in the simplest form do:
if (argc < 2) return -1; // check if any argument was passed, as pm100 said in comments to this answer.
FILE *f = fopen(argv[1], "rb"); // change "rb" to mode you need
if (f==NULL) return -1; // file could not be opened
// process the file as you need from here
...
}
The alternative approach, reading user input at runtime using fgets
could be found here. Then pass the string you got from user as an first argument to fopen
.
You can, of course, mix these two approaches (checking if any command-line args were passed, and if not ask for user input) but this probably would be an overkill for a homework.
If you just need to load file from a fixed place in your filesystem, and filename won't change then simply change argv
from my example to your filename or path:
int main()
{
const char filename[] = "your_file_name_here";
FILE *f = fopen(filename, "rb"); // change "rb" to mode you need
if (f==NULL) return -1; // file could not be opened
// process the file as you need from here
...
}