Detect EOF on a fgets While Loop

2019-08-20 03:36发布

问题:

I'm looping through each line of a TCP socket input using fdopen and fgets like this:

int connfd = accept(listenfd, (struct sockaddr*)NULL, NULL);
FILE *f;
char line[1024];

f = fdopen(connfd, "a+");
while(fgets(line, sizeof(line), f) != NULL) {
    printf("%s", line);
}

printf("EOF");
fclose(f);

The problem is that it looks like fgets never returns NULL for some strange reason. Is there any other way to check for EOF?

回答1:

You'll only receive and end of file on a socket if the socket gets closed.

If you need to stop reading while keeping the socket open, you need to define a protocol for that.