Here is a snippet from the code I wrote that has been causing my console application to crash...
FILE *pfile;
char *receivedmsg;
int bytes_received, bufflen = 4000;
int iFileDescriptor /* valid SOCKET */
receivedmsg = (char *)malloc(sizeof(bufflen));
/* checking omitted */
pfile = fopen("Test.html", "w");
if(pfile == NULL) {
printf("Could create file...exiting.\n");
return 0;
}
while(bytes_received) {
bytes_received = recv(
iFileDescriptor
,receivedmsg
,bufflen /* this is what I set the buffer size to */
,0
);
if(bytes_received == -1) {
printf("An error occurred while receiving message from remote server.\n");
break;
}
else if(bytes_received == 0) {
printf("Remote server closed connection.\n");
break;
}
else {
if(!fwrite(receivedmsg, sizeof(char), bytes_received, pfile))
printf("An error occurred while writing to file!\n");
}
}
} /* End of while loop */
I have already isolated the problem -- it is the fwrite function call. I confirmed this by trying the above code with the API calls _lopen and _lwrite instead of fopen and fwrite, which worked perfectly. Problem solved, right? Wrong, because my objective is to find out WHY fwrite did not work. Any ideas regarding why fwrite is not working in this example?? -- I suspect pfile is the problem.
Additional information:
When testing I established a sockets connection between my computer and CNN's server. I attempted to download their home page.
Yes, I parsed out the portion of the server response that includes some binary data, which appeared between the response header and the HTML code in this case. (Does any one know why that binary data is included?)
I also tried fputs, which also resulted in a crash. That is why I suspect pfile, the stream, is the problem.
I tried several variations of the fwrite call, which included: fwrite(receivedmsg, sizeof(bytes_received), 1, pfile); - and several others, none worked.
I tried using char receivedmsg[4000] instead of dynamically allocating the memory -- same result.
There must be a way to do this using C, right? What am I doing wrong?
Thanks in advance.