Answers for "how to read a file line by line in c"

C
3

read file in c line by line

#include <stdio.h>

int main(int argc, char* argv[])
{
    char const* const fileName = argv[1]; /* should check that argc > 1 */
    FILE* file = fopen(fileName, "r"); /* should check the result */
    char line[256];

    while (fgets(line, sizeof(line), file)) {
        /* note that fgets don't strip the terminating \n, checking its
           presence would allow to handle lines longer that sizeof(line) */
        printf("%s", line); 
    }
    /* may check feof here to make a difference between eof and io failure -- network
       timeout for instance */

    fclose(file);

    return 0;
}
Posted by: Guest on May-03-2021
0

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]);
    }
}

/*
	[birryree@lilun c_code]$ ./a.out hello there
	argv[0]: ./a.out
	argv[1]: hello
	argv[2]: there
*/
Posted by: Guest on November-26-2020
0

c read a whole string from a file

#define  _GNU_SOURCE  //Necessary for getline to work with clang in Ubuntu
getline(&line, &len, fp);
Posted by: Guest on November-01-2020

Code answers related to "how to read a file line by line in c"

Code answers related to "C"

Browse Popular Code Answers by Language