Question: How do I open text files in C through command line arguments? I'm trying to open and print a file with the command line argument.
How do I open text files in C through command line arguments?
I'm trying to open and print a file with the command line argument. From what I've been reading it says that my text files need to be in the same directory with the c program but I'm not sure what that even means or what approach I have to take to get there.
I'm hoping I'm on the right track as far as the code, but where do my files need to be located in order for them to be read?
int main(int argc, char *argv[]) {
if ( argc != 2 ) { printf("No file to open "); return; } else { FILE *file = fopen(argv[1], "r");
if ( file == 0 ) { printf( "Could not open file " ); } else { int x; while ((x = fgetc(file)) != EOF) { printf("%d", x); } fclose(file); } } return 0; }
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
