Thread: Reading a file in 1-kilobyte chunks...

  1. #1
    Newbie Crilston's Avatar
    Join Date
    Jun 2005
    Location
    Montreal, Canada
    Posts
    8

    Reading a file in 1-kilobyte chunks...

    How do I read a file in 1 KB chunks and send them to a client? Here's the server:
    Code:
    SOCKET s = accept(Socket, NULL, NULL);
    if (s != SOCKET_ERROR)
    {
        char filename[MAX_PATH] = "";
        recv(s, filename, MAX_PATH, 0);
        if (filename)
        {
            FILE *f = fopen(filename, "rb");
            if (f)
            {
                char buf[1024] = "";
                while (feof(f) == 0)
                {
                    fread(buf, 1024, 1, f);
                    send(s, buf, (int) strlen(buf), 0);
                }
            }
            fclose(f);
        }
        closesocket(s);
    }
    And here's the client:
    Code:
    char filename[MAX_PATH] = "OMGWTF.txt";
    send(Socket, filename, MAX_PATH, 0);
    int len;
    char buf[1024];
    FILE *f = fopen(filename, "wb");
    do
    {
        len = recv(Socket, buf, 1024, 0);
        fwrite(buf, len, 1, f);
    } while (len != 0);
    fclose(f);
    The received file is about 2 times larger than the original. What's wrong?

  2. #2
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Well for starters, stop using feof to control your loop. Read the FAQ if you want to know why it's wrong. Why are you opening in binary mode, and then treating the contents like a string? Why are you ignoring the return value of fread? Etc., etc.


    Quzah.
    Hope is the first step on the road to disappointment.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Newbie homework help
    By fossage in forum C Programming
    Replies: 3
    Last Post: 04-30-2009, 04:27 PM
  2. sequential file program
    By needhelpbad in forum C Programming
    Replies: 80
    Last Post: 06-08-2008, 01:04 PM
  3. Can we have vector of vector?
    By ketu1 in forum C++ Programming
    Replies: 24
    Last Post: 01-03-2008, 05:02 AM
  4. System
    By drdroid in forum C++ Programming
    Replies: 3
    Last Post: 06-28-2002, 10:12 PM