UC3M

Telematic/Audiovisual Syst./Communication Syst. Engineering

Systems Architecture

September 2017 - January 2018

8.4.2.  The getline function

The GNU library provides the nonstandard getline function that makes it easy to read lines reliably:

#include <stdio.h>
ssize_t getline(char **lineptr, size_t *n, FILE *stream);

This function reads an entire line from stream, storing the text (including the newline and a terminating null character) in a buffer and storing the buffer address in *lineptr. Before calling getline, you should place in *lineptr the address of a buffer *n bytes long, allocated with malloc. If this buffer is long enough to hold the line, getline stores the line in this buffer. Otherwise, getline makes the buffer bigger using realloc, storing the new buffer address back in *lineptr and the increased size back in *n.

When getline returns, *lineptr is a char * which points to the text of the line. When successful, it returns the number of characters read (including the newline, but not including the terminating null); if an error occurs or end of file is reached, getline returns -1.

Note

When you have to read in a line of text from the keyboard, do it with getline; you will avoid future problems.

The following program demonstrates how to use getline to read a line of text from the keyboard safely. Try typing more than 10 characters. Notice that getline can safely handle that line, no matter how long it is.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include <stdio.h>
#define MAX_LENGTH 10

int main(void)
{
  ssize_t bytes_read;  
  size_t bytes_number;
  //size_t and ssize_t are unsigned int types.
  char *string;

  puts("Please enter a line of text:\n");
  
  /* You can initialize the arguments by yourself: */
  //bytes_number = MAX_LENGTH;
  //string = (char *) malloc (bytes_number+ 1);
  //bytes_read = getline(&string, &bytes_number, stdin);
  
  /*Or let getline do it for you by setting the number to 0 and the string to NULL.*/
  bytes_number = 0;
  string = NULL;  
  bytes_read = getline(&string, &bytes_number, stdin);

  if (bytes_read == -1)
  {
    puts("ERROR!");
  }
  else
  {
    puts("You typed:");
    puts(string);
  }
  free(string)
  return 0;
}

Check with these questions if you understood this document

  1. Mark the WRONG sentence regarding the getline function:

    • Returns the number of read chars, including '\n'. It does not include the '\0'.

    • If the memory buffer has no enough space to store the read line, getline returns an error.

    • If the pointer to the memory buffer that receives as parameter is NULL, it internally allocates memory with a call to malloc.