C++: Read files in 4096B steps [duplicate]

2019-08-30 06:52发布

问题:

This question already has an answer here:

  • Reading and writing binary file 7 answers

I want to write a ftp class with sockets, textfiles work pretty well to upload so far, but then I wanted to upload a bigger file, a movie, and it didn't work.

The first 4096B are read well, but then it reads just nothing more.

Maybe i'am using the wrong functions, please help my with my code.

Here's my read function:

bool CStream::Read  (string * _OutString, unsigned int _iStartPos, unsigned int _iLength)
{
    if (!bInitialized)
        return false;

    int iReturn = 0;

    char * buffer;

    fseek (pFile, _iStartPos, SEEK_SET);

    buffer = new char[(unsigned int) _iLength + 1];

    iReturn = fread  (buffer, 1, (unsigned int) _iLength, pFile);

    if (iReturn == 0)
    {
        delete (buffer);

        return false;
    }
    else
        buffer[iReturn] = '\0';

    *_OutString = string (buffer, iReturn);

    delete (buffer);

    return true;
}

and that's how I call it:

Stream.Read is the function on top

Stream.FileSize (&iFileSize);

    while (iPos < iFileSize)
    {
        Stream.Read (&ReadData, iPos, 4096);

        Socket.Send   (ReadData, NULL, NULL);
        Socket.Reciev (&RecievData, NULL, NULL);

        if (RecievData != "ok")
            goto Error;

        iPos += 4096;
    }

回答1:

You are currently waiting for an ok response every iteration of the while loop.

There are a few other things that you should really look at doing to get a better result:

  1. Open the file you're transferring once, read from it in blocks each iteration, then close it once. Opening and closing it multiple times is not good

  2. As others have mentioned, you have mixed array-new with delete. Use array delete, ie. delete [] buffer;

  3. Don't use strings as your intermediate buffer type!