1

I have a text file contains a 4 words ; each one in a line , which function allows me to control the lines ; like i want to read the first line only and after move to the next line ( equivalent to \n in console) and store each one in a string

bwass31
  • 65
  • 1
  • 10

1 Answers1

3

There are two major functions that read input line-by-line:

  • If you have a pre-allocated buffer, use fgets.
  • If you want the buffer allocated for you, use getline (note that it only conforms to POSIX 2008 and above).

Using fgets

#include <stdio.h> // fgets
FILE *f = stdin;

char buf[4096]; // static buffer of some arbitrary size.
while (fgets(buf, sizeof(buf), f) == buf) {
    // If a newline is read, it would be at the end of the buffer. The newline may not be read if fgets() reaches the buffer limit, or if EOF is reached, or if reading the file is interrupted.
    printf("Text: %s\n", buf);
}

Using getline

#define _POSIX_SOURCE 200809L // getline is not standard ISO C, but rather part of POSIX.
#include <stdio.h> // getline
#include <stdlib.h> // free

FILE *f = stdin;
char *line = NULL;
size_t len = 0;
ssize_t nread;

while (nread = getline(&line, &len, f)) != 1) {
    // Note that the newline \n is always stored unless it reached EOF first.
    // len stores the current length of the buffer, and nread stores the length of the current string in the buffer. getline() grows the buffer for you whenever it needs to.
    printf("New line read: %s", line);
}

// It's the programmer's job to free() the buffer that getline() has allocated
free(line);
Samuel Hunter
  • 527
  • 2
  • 11
  • You forgot: "if you want maximal performance&flexibility: use getc() and a state machine". – wildplasser Mar 09 '21 at 00:23
  • 1
    free(line) can be used for stack data buffer ? – bwass31 Mar 09 '21 at 00:27
  • 2
    Returning `NULL` from `strchr(buf, '\n')` doesn't necessarily indicate *"Part of very large line read: "*. It is also possible that the stream doesn't end with a `'\n'`. – M. Nejat Aydin Mar 09 '21 at 01:15
  • @M.NejatAydin Right, my mistake, I edited the example code so it doesn't try to do anything smart with the newline. – Samuel Hunter Mar 09 '21 at 01:20
  • OP probably also wants to remove the newline character from the input. In that case, this question will also be relevant: [Removing trailing newline character from fgets() input](https://stackoverflow.com/q/2693776/12149471) – Andreas Wenzel Mar 09 '21 at 03:08