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

丶灬走出姿态 提交于 2019-12-11 16:35:01

问题


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!



来源:https://stackoverflow.com/questions/24712427/c-read-files-in-4096b-steps

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!