How to let fgets not stop reading at \n?

114 Views Asked by At

I want to read a fixed length of chars from a file. Therefore I use fgets, but fgets stops at "\n" reading.

How can I read the first N char even though one of them is a newline character?

I tried searching for other functions in the documentation but found none.

2

There are 2 best solutions below

1
chqrlie On

To read a fixed number of bytes from a stream, you should use fread:

#include <stdio.h>

size_t fread(void * restrict ptr, size_t size, size_t nmemb,
             FILE * restrict stream);

fread attempts to read nmemb elements of size bytes each and returns the number of elements successfully read. It returns 0 at end of file.

Also make sure the file is opened in binary more with "rb" to prevent the translation of line ending sequences on legacy systems that may interfere with the byte counts.

3
gulpr On

To be sure that your string is null character terminated you need to write your own function

char *freads(char *buff, size_t len, FILE *fi)
{
    size_t readBytes = fread(buff, 1, len - 1, fi);

    if(!readBytes) return NULL;
    buff[readBytes] = 0;
    return buff;
}