getline() is preferred than gets(), fgets(), and scanf()..

Home Forums C-programming.. getline() is preferred than gets(), fgets(), and scanf()..

Viewing 2 posts - 1 through 2 (of 2 total)
  • Author
    Posts
  • #2486 Reply
    Humble
    Keymaster

    Yes, functions like gets(), fgets() and scanf()..etc are unreliable..

    The getline() function reads an entire line from a stream, up to and including the next newline character.

    ssize_t getline(char **lineptr, size_t *n, FILE *stream);

     
          getline() reads an entire line from stream, storing the address of the buffer containing the text into *lineptr.  The buffer is null-termi‐
           nated and includes the newline character, if one was found.
    
           If *lineptr is NULL, then getline() will allocate a buffer for storing the line, which should be freed by the user program.  (In this case,
           the value in *n is ignored.)
    
           Alternatively, before calling getline(), *lineptr can contain a pointer to a malloc(3)-allocated buffer *n bytes in size.  If the buffer is
           not large enough to hold the line, getline() resizes it with realloc(3), updating *lineptr and *n as necessary.
    
           In either case, on a successful call, *lineptr and *n will be updated to reflect the buffer address and allocated size respectively
    
    
    
           In either case, on a successful call, *lineptr and *n will be updated to reflect the buffer address and allocated size respectively.
    
    
      The getline function will automatically enlarge the block of memory as needed, using realloc() function, so there is never a shortage of space aand its one of reason why getline is so safe.  getline() will also tell the new size of the block by the value returned in the second parameter.
    
    If an error occurs, such as end of file being reached without reading any bytes, getline returns -1. Otherwise, the first parameter will contain a pointer to the string containing the line that was read, and getline returns the number of characters read (up to and including the newline, but not the final null character). The return value is of type ssize_t.
    
    
    
    	FILE *fp;
    
    	char *lines = NULL;
    
    	size_t n = 0;
    	ssize_t read;
    	
    	fp = fopen("/etc/hosts" , "r");
    	if (fp == NULL)
    	{
    		printf ("Failed to open file");
    		exit(EXIT_FAILURE);
    	}
    
    	while (( read = getline(&lines, &n , fp)) != -1)
    	{
    		   printf("Lenght of line %zu :\n", read);
               	   printf("%s", lines);
    
    	}
    		free(lines);
    		printf ("Successfully read");
    	return 0;
    
    
    
    
    
    
    #2488 Reply
    Humble
    Keymaster
    This reply has been marked as private.
Viewing 2 posts - 1 through 2 (of 2 total)
Reply To: getline() is preferred than gets(), fgets(), and scanf()..
Your information: