read file in c line by line code example
Example 1: read file in c line by line
#include <stdio.h>
int main(int argc, char* argv[])
{
char const* const fileName = argv[1];
FILE* file = fopen(fileName, "r");
char line[256];
while (fgets(line, sizeof(line), file)) {
printf("%s", line);
}
fclose(file);
return 0;
}
Example 2: read from command line c
#include <stdio.h>
int main(int argc, char **argv) {
for (int i = 0; i < argc; ++i) {
printf("argv[%d]: %s\n", i, argv[i]);
}
}
Example 3: c read a whole string from a file
#define _GNU_SOURCE
getline(&line, &len, fp);
Example 4: c read file from command line
You can use as your main function:
int main(int argc, char **argv)
So, if you entered to run your program:
C:\myprogram myfile.txt
argc will be 2
argv[0] will be myprogram
argv[1] will be myfile.txt
To read the file:
FILE *f = fopen(argv[1], "r");