简体   繁体   中英

Does fgets() hold somehow where it stopped reading from a FILE *?

I am trying to get a sample (shell script) program on how to write to a file:

#include <unistd.h>
#include <stdio.h>
#include <string.h>
int main(int argc, char **argv){
  char buff[1024];
  size_t len, idx;
  ssize_t wcnt;
  for (;;){
    if (fgets(buff,sizeof(buff),stdin) == NULL)
      return 0;
    idx = 0;
    len = strlen(buff);
    do {
      wcnt = write(1,buff + idx, len - idx);
      if (wcnt == -1){ /* error */
        perror("write");
        return 1;
      }
      idx += wcnt;
    } while (idx < len);
  }
}

So my problem is this: Let's say I want to write a file of 20000 bytes so every time I can only write (at most) 1024 (buffer size).
Let's say that in my first attempt everything is going perfect and fgets() reads 1024 bytes and in my first do while I write 1024 bytes.
Then, since we wrote "len" bytes we exit the do-while loop.
So now what?? The buffer is full from our previous reading. It seems to me that for some reason it is implied that fgets() will now continue reading from the point it reached in in-file the last time. (buf[1024] here).
How come, fgets() knows where it stopped reading in the in-file?
I checked the man page:

fgets() reads in at most one less than size characters from stream and stores them into the buffer pointed to by s. Reading stops after an EOF or a newline. If a newline is read, it is stored in the buffer. A terminating null byte (aq\0aq) is stored after the last character in the buffer.
fgets() return s on success, and NULL on error or when the end of file occurs while no characters have been read.*

So from that, I get that it returns a pointer to the first element of buf, which is always buf[0], that's why I am confused.

When using a FILE stream, it contains information about the position in the file (among other things). fgets and other functions like fread or fwrite merely utilize this information and updates it when an operation is performed. So, whenever fgets reads from the stream, the stream will be updated to maintain the position, so that the next operation starts off where the previous ended.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM