Thread: File transfer

  1. #1
    Registered User scrapedbr's Avatar
    Join Date
    May 2003

    File transfer

    I'm creating a file server...

    The problem is when i reach end of file. In server's side, the message is Connection reset by peer, and the client create a file whith a wrong size (multiple of buffer size).
    I want to transfer any types of file. I am using a tar.gz with 20k for tests..

    Server's side.
    char buffer[10000];
    /* the filesize */
    bytes_write = write(data->client_fd, &filesize, sizeof(filesize));
    	if( fgets( out_buffer, BUFFER, fd ) != NULL )
    		bytes_write = write(data->client_fd, out_buffer, BUFFER);
    		if (bytes_write < 0){
    Client's side:
    char buffer[10000];
    /* receive the file size */
    bytes_read = read(socket_fd, &filesize, sizeof(filesize));
    tmp = 0;
    while(tmp <= filesize){
    	bytes_read = read(socket_fd, buffer, BUFFER);
    	if (bytes_read < 0){
    		perror("\nReceiving data\n");
    	/* write in the output file */
    	fwrite(buffer, 1, bytes_read, fd);
    	tmp+= bytes_read;
    I see the problem in tmp because it will be a multiple of buffer size. But, how i can do this correctly ?
    Gobolinux user: 00101100

  2. #2
    Yes, my avatar is stolen anonytmouse's Avatar
    Join Date
    Dec 2002
    fgets() is used only for reading text files. Typically, you would determine the length of the text returned after calling fgets() using:
    len = strlen(buffer);
    but since you are reading a binary file, it is going to contain embedded nul characters and return the wrong length. Therefore, you must use the read() or fread() functions which will return the number of elements read. You can then use this value in your call to fwrite() or write(), exactly like you are doing in your client side code.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. File transfer- the file sometimes not full transferred
    By shu_fei86 in forum C# Programming
    Replies: 13
    Last Post: 03-13-2009, 12:44 PM
  2. Possible circular definition with singleton objects
    By techrolla in forum C++ Programming
    Replies: 3
    Last Post: 12-26-2004, 10:46 AM
  3. System
    By drdroid in forum C++ Programming
    Replies: 3
    Last Post: 06-28-2002, 10:12 PM
  4. me take a look at this: File Encryptor
    By heljy in forum C Programming
    Replies: 3
    Last Post: 03-23-2002, 10:57 AM
  5. Need a suggestion on a school project..
    By Screwz Luse in forum C Programming
    Replies: 5
    Last Post: 11-27-2001, 02:58 AM