Re: [Dev-C++] write and fwrite functions
Open Source C & C++ IDE for Windows
Brought to you by:
claplace
|
From: Per W. <pw...@ia...> - 2005-04-11 16:07:06
|
You really can not call write() until you have checked the result of the
recv() call. If recv() returns an error, you add -1 to totalRcvd but you
then make assumptions about what write() would do for a write of length
-1.
One other thing. Don't repeat your loop only breaking on bytesRecv=0. That
would get you in an infinite loop in case you get a permanent error on the
socket. The only time it is meaningful to repeat the recv() call is if
errno gets set to EAGAIN or EINTR.
A better loop would look something like:
int nRead,nWritten,nTotal = 0;
for (;;) {
nRead = recv(sock,recvbuf,DATA_BUFSIZE,0);
if (nRead < 0) {
if (errno == EAGAIN || errno == EINTR) continue;
printf("Failed recv() - (%s)\n",strerror(errno));
return -1;
}
if (nRead == 0) {
// end of file
break;
}
nWritten = write(fd,recvbuf,nRead);
if (nWritten != nRead) {
printf("Failed write() - (%s)\n",strerror(errno));
return -1;
}
nTotal += nWritten;
}
return 0;
/Per W
On Mon, 11 Apr 2005, Dmitry Sidorov wrote:
> Hello, dev-cpp-users.
>
> I try to save binary data recieved from TCP socket into the file
>
> ...
>
> #define DATA_BUFSIZE 4096
>
> long totalRcvd = 0;
> long nFileSize = 0;
> int bytesRecv = SOCKET_ERROR;
> char recvbuf[DATA_BUFSIZE];
> int fd = open( "filename", O_CREAT|O_WRONLY );
> while( bytesRecv == SOCKET_ERROR || bytesRecv > 0 ) {
> bytesRecv = recv( sock, recvbuf, DATA_BUFSIZE, 0 );
> totalRcvd += bytesRecv;
> nFileSize += write( fd, recvbuf, bytesRecv );
> }
> close( fd );
>
> totalRcvd and nFileSize are equal
> nFileSize value is valid (I sent the same quantity of bytes to socket)
>
> But real file size is bigger as nFileSize
> And it is broken :(
>
> When I use fopen, fwrite and fclose functions the result is rhe same
>
> Why?
>
>
> --
> Dmitry
>
>
>
> -------------------------------------------------------
> SF email is sponsored by - The IT Product Guide
> Read honest & candid reviews on hundreds of IT Products from real users.
> Discover which products truly live up to the hype. Start reading now.
> http://ads.osdn.com/?ad_id=6595&alloc_id=14396&op=click
> _______________________________________________
> Dev-cpp-users mailing list
> Dev...@li...
> TO UNSUBSCRIBE: http://www23.brinkster.com/noicys/devcpp/ub.htm
> https://lists.sourceforge.net/lists/listinfo/dev-cpp-users
>
|