Detect EOF on a fgets While Loop

限于喜欢 提交于 2019-12-11 18:12:12

问题


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.



来源:https://stackoverflow.com/questions/13443122/detect-eof-on-a-fgets-while-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!