Shri Shri - 4 months ago 18
C Question

How do I read a line from a file in c?

I am having a requirement to read a file line by line through a c program.
I know I can do it very straight by using a FILE pointer and using

(if by fixed length string) or
(if by character by character). The only point here to note is that the length of a line in the file can be different. So , if i am using

char *fgets(char *__restrict s, int n, FILE *__restrict stream);

I do not know the value of "int n" here since it can vary from line to line in the file.

I searched for an answer for this query but i got to know the usage of
function which is c++ function. The only way for me is to read each character until i encounter a '\n' and get that copied to a string.

Is there any other way to do this straight in a c program ?


I do not know the value of "int n" here since it can vary from line to line in the file.

The above and other discussion implies OP wants code that auto-sizes the buffer to whatever the line length may be. fgets() does the job fine if you are willing to accept a max length. Read the line and then copy in to a right-sized buffer.

  #define BUF_SIZE 1000
  char buf[BUF_SIZE];

  while (fgets(buf, sizeof buf, stream)) {

    // Add long line detection here if desired

    char *s = strdup(buf);

If code does not want to impose any maximum length, IMO, that is a weak design. Certainly lines can be very long and BUF_SIZE above should be a very generous value, but to allow code to handle lines of any length is to give control of the program to external forces be it a file or user input. That is the basis of a hacker exploit. The given application should have a liberal upper bound of the acceptable line length. fgets() provides that - although it does have other weaknesses. The common *nix getline() allows external forces to cause your program to consume up to SIZE_MAX byte in one call - not defensive code.