Detect EOF on a fgets While Loop

2019-08-20 03:30发布

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条回答
狗以群分
2楼-- · 2019-08-20 04:10

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.

查看更多
登录 后发表回答