I'm working on a proxy server in c. I've gotten rather far using a combination of fread and fgets in different places but would like to reconcile and understand the difference. In the following example, I'm trying to use fread in a place i previously used fget successfully. Instead my server now hangs at the fread line. What's the difference and why is my program hanging?
void HandleTCPClient(int clntSocket)
{
FILE *request = fdopen(clntSocket, "r");
char reader[2000];
size_t q; //typo before
while((q=fread(reader, 1, sizeof(reader), request))>0) { //hangs here!
printf("i read something!\n");
}
return;
}
thanks!!
EDIT: so if i make the line "while((q=fread(reader, 1, 1, request))>0) {"
i get "i read something" all over my screen...
not sure what this means. So is it correct that fread will literally do nothing if there isn't at least your buffer's size number of characters present in the stream?
fgets
returns when a newline is read whilefread
will block until requested number of bytes are available in the stream or on EOF. In your case, the call blocks because you do not have 2000 bytes of data ready in the stream.Using
fread()
instead ofrecv()
to read on a TCP socket seems strange to me..?Anyway,
fread
is blocking as long as there is nothing to read. You should always check that a socket is ready to perform reading or writing, usingselect()
for example on linux.