Kee Nops
Kee Nops

Reputation: 43

How to read beyond new line characters using fgets() function?

I understand from C manpage that using fgets(), reading stops after an EOF or a newline. i have a program that reads from file(with multiple lines) and reading stop at the end of new line.

Is there a way to forcefgets() to ignore newlines and read till EOF?

while(fgets(str,1000, file))
{ 
 // i do stuffs with str here
}

Upvotes: 0

Views: 2614

Answers (3)

samuil ivanov
samuil ivanov

Reputation: 31

In the while loop you have to make the following check:

while ((fgets(line, sizeof (line), file)) != NULL)

On success, the function returns the same str parameter. If the End-of-File is encountered and no characters have been read, the contents of str remain unchanged and a null pointer is returned. If an error occurs, a null pointer is returned.

code example:

#include <stdio.h>
int main()
{
    char *filename = "test.txt";
    char line[255];
    FILE *file;
    file = fopen(filename, "r");
    while ((fgets(line, sizeof (line), file)) != NULL) {
        printf("%s", line);
    }
    fclose(file);
    return 0;
}

Upvotes: 1

One Man Crew
One Man Crew

Reputation: 9578

NO, fgets stops reading after it encounters a \n (new line) character.

Otherwise, you must find and remove the newline yourself.

Or you can use fread:

The C library function size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream) reads data from the given stream into the array pointed to, by ptr.

The total number of elements successfully read are returned as a size_t object, which is an integral data type. If this number differs from the nmemb parameter, then either an error had occurred or the End Of File was reached.

/* fread example: read an entire file */
#include <stdio.h>
#include <stdlib.h>

int main () {
  FILE * pFile;
  long lSize;
  char * buffer;
  size_t result;

  pFile = fopen ( "myfile.bin" , "rb" );
  if (pFile==NULL) {fputs ("File error",stderr); exit (1);}

  // obtain file size:
  fseek (pFile , 0 , SEEK_END);
  lSize = ftell (pFile);
  rewind (pFile);

  // allocate memory to contain the whole file:
  buffer = (char*) malloc (sizeof(char)*lSize);
  if (buffer == NULL) {fputs ("Memory error",stderr); exit (2);}

  // copy the file into the buffer:
  result = fread (buffer,1,lSize,pFile);
  if (result != lSize) {fputs ("Reading error",stderr); exit (3);}

  /* the whole file is now loaded in the memory buffer. */

  // terminate
  fclose (pFile);
  free (buffer);
  return 0;
}

Upvotes: 0

H.S.
H.S.

Reputation: 12634

Is there a way to force fgets() to ignore newlines and read till EOF?

No, you can't because fgets() is implemented in such a way that the parsing will stops if end-of-file occurs or a newline character is found. May you can consider using other file i/o function like fread().

Upvotes: 2

Related Questions