1#include <stdio.h>
2
3int main(int argc, char* argv[])
4{
5 char const* const fileName = argv[1]; /* should check that argc > 1 */
6 FILE* file = fopen(fileName, "r"); /* should check the result */
7 char line[256];
8
9 while (fgets(line, sizeof(line), file)) {
10 /* note that fgets don't strip the terminating \n, checking its
11 presence would allow to handle lines longer that sizeof(line) */
12 printf("%s", line);
13 }
14 /* may check feof here to make a difference between eof and io failure -- network
15 timeout for instance */
16
17 fclose(file);
18
19 return 0;
20}
1#include <stdio.h>
2
3int main(int argc, char **argv) {
4 for (int i = 0; i < argc; ++i) {
5 printf("argv[%d]: %s\n", i, argv[i]);
6 }
7}
8
9/*
10 [birryree@lilun c_code]$ ./a.out hello there
11 argv[0]: ./a.out
12 argv[1]: hello
13 argv[2]: there
14*/
1#define _GNU_SOURCE //Necessary for getline to work with clang in Ubuntu
2getline(&line, &len, fp);
1You can use as your main function:
2int main(int argc, char **argv)
3
4So, if you entered to run your program:
5C:\myprogram myfile.txt
6
7argc will be 2
8argv[0] will be myprogram
9argv[1] will be myfile.txt
10
11To read the file:
12FILE *f = fopen(argv[1], "r");