fangio
fangio

Reputation: 1786

C fgets buffersize

I have a program in C, which reads in a file with buffers:

char buffer[65536];
while(fgets(buffer,65536,inputFile)){...}

Now I have some questions:

  1. What happens if the filesize is smaller than buffersize?
  2. Does fgets() overwrite the full buffer, so if previous buffer (buffer1) was full, and the next one (buffer2) for example size 10 isn't, will the buffer still have the chars of buffer1 in it for example at buffer2[20] = buffer1[20] because it didn't overwrite?
  3. How to know how many chars are inside the buffer, so you can backward loop the buffer

Upvotes: 1

Views: 5974

Answers (2)

Chung Lim
Chung Lim

Reputation: 179

To answer your questions, firstly you must understand fgets(3). It reads a line at once, fgets() returns after newline or EOF is reached. And a '\0' is appended to terminate the string. I answer to your question as followings...

  1. Normally fgets() takes a line of string at a time not the entire file. In your code, it means the line has maximum length of 65535 + '\0' makes 65536, which is considered too long. To read a text file, normally you have to put fgets() in for () or while () loop until EOF is reached (buffer == NULL).
  2. If it reads a line, which is longer than the length of buffer, it will read only buffer length - 1 chars, then append '\0'.
  3. strlen(3) will give you the length of the string.

Upvotes: 3

kabanus
kabanus

Reputation: 25895

As the comments suggest, the man can help here, or google... From cppreference

Reads at most count - 1 characters from the given file stream and stores them in the character array pointed to by str. Parsing stops if end-of-file occurs or a newline character is found, in which case str will contain that newline character. If no errors occur, writes a null character at the position immediately after the last character written to str.

and also:

Return value: str on success, null pointer on failure.

Basically the number is the amount of chars you read+1. Usually you don't gobble the whole line but only some of it. In any case the buffer has a null terminator and you can keep reading until EOF.

Upvotes: 1

Related Questions