Thread: recv data into file

  1. #1
    Registered User
    Join Date
    Feb 2006
    Posts
    71

    recv data into file

    OK I want directly store the data I get from a recv command into a file, without posting the data firstly into the char buf, because if I received a binary file over recv it stops at some points in the binary file.
    Any ideas? Thanks for help.

    Code:
                    char buf[4096];
    	FILE * pFile;
    	pFile = fopen ("download.txt" , "wb");
    
    here comes some code to open the connection.
    
    	while ( (tlen=recv( h, buf, sizeof(buf), 0 )) > 0 ) {
    		fputs (buf , pFile);
    	}
    
    fclose (pFile);

  2. #2
    Registered User
    Join Date
    Jan 2005
    Posts
    847
    Don't use string functions like fputs with what you get from a recv call. There is no guantee that it willl be null terminated (as pointed out in this thread) and this may well be the source of your problem when recieving a binary file.

    Use fwrite, and use the number of bytes returned by recv() as the amount of bytes to write to the file. Loop untill you get a 0 or -1(error).
    Last edited by Quantum1024; 05-24-2006 at 08:29 AM.

  3. #3
    Registered User
    Join Date
    Feb 2006
    Posts
    71
    Quote Originally Posted by Quantum1024
    Don't use string functions like fputs with what you get from a recv call. There is no guantee that it willl be null terminated (as pointed out in this thread) and this may well be the source of your problem when recieving a binary file.

    Use fwrite, and use the number of bytes returned by recv() as the amount of bytes to write to the file. Loop untill you get a 0 or -1(error).
    Now I have it that way:
    It works but only until j reaches the size of buf, here 4096, how can I make the buf char as big as the file I recive?

    Code:
       		unsigned int j = 0;
    		do { 
    			if (recv(h,&buf[j],1,0)==SOCKET_ERROR) {
    				addlog("retlinehttp(): recv() Failed! %d", WSAGetLastError());
    				return -2;
    			}
    			fwrite (&buf[j] , 1 , 1 , file);
    			j++;
    		} while (j < sizeof(buf));

  4. #4
    Registered User
    Join Date
    Jan 2005
    Posts
    847
    allocate the buffer using new. When j reaches the end of the buffer allocate another, bigger buffer and coppy the contents then delete the old one.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. opening empty file causes access violation
    By trevordunstan in forum C Programming
    Replies: 10
    Last Post: 10-21-2008, 11:19 PM
  2. Replies: 48
    Last Post: 09-26-2008, 03:45 AM
  3. Bitmasking Problem
    By mike_g in forum C++ Programming
    Replies: 13
    Last Post: 11-08-2007, 12:24 AM
  4. gcc link external library
    By spank in forum C Programming
    Replies: 6
    Last Post: 08-08-2007, 03:44 PM
  5. File Database & Data Structure :: C++
    By kuphryn in forum C++ Programming
    Replies: 0
    Last Post: 02-24-2002, 11:47 AM