Telling和seekg以及文件读取不起作用

Tellg and seekg and file read not working

本文关键字:文件 读取 不起作用 seekg Telling      更新时间:2023-10-16

我试图在缓冲区中以二进制模式从文件中一次读取64000个字节,直到文件结束。我的问题是tellg()以十六进制值返回位置,我如何使它返回十进制值?因为我的if条件不起作用,它的读数超过64000,当我重新定位我的pos和size_stream时(size_stream=size_stream-63999;pos=pos+63999;),它每次都指向错误的位置。

如何在二进制模式下一次将64000个字节从文件读取到缓冲区,直到文件结束?

如有任何帮助,将不胜感激

  std::fstream fin(file, std::ios::in | std::ios::binary | std::ios::ate);
    if (fin.good())
    {
        fin.seekg(0, fin.end);
        int size_stream = (unsigned int)fin.tellg(); fin.seekg(0, fin.beg);
        int pos = (unsigned int)fin.tellg();
        //........................<sending the file in blocks  
        while (true)
        {
            if (size_stream > 64000)
            {
                fin.read(buf, 63999);
                buf[64000] = '';
                CString strText(buf);
                SendFileContent(userKey,
                    (LPCTSTR)strText);
                size_stream = size_stream - 63999;
                pos = pos + 63999;
                fin.seekg(pos, std::ios::beg);
            }
            else
            {
                fin.read(buf, size_stream);
                buf[size_stream] = '';
                CString strText(buf);
                SendFileContent(userKey,
                    (LPCTSTR)strText); break;
            }
        }

我的问题是tellg()返回十六进制值中的位置

不,不是。它返回一个整数值。您可以以十六进制显示值,但不会以十六进制返回

当我重新定位pos和size_stream(size_stream=size_stream-63999;pos=pos+63999;)时,它每次都指向错误的位置。

你一开始就不应该寻求。执行读取后,将文件留在原来的位置。下一次读取将从上一次读取结束的位置开始。

如何在二进制模式下一次将64000个字节从文件读取到缓冲区,直到文件结束?

做一些更像这样的事情:

std::ifstream fin(file, std::ios::binary);
if (fin)
{
    unsigned char buf[64000];
    std::streamsize numRead;
    do
    {
        numRead = fin.readsome(buf, 64000);
        if ((!fin) || (numRead < 1)) break;
        // DO NOT send binary data using `LPTSTR` string conversions.
        // Binary data needs to be sent *as-is* instead.
        //
        SendFileContent(userKey, buf, numRead);
    }
    while (true);
}

或者这个:

std::ifstream fin(file, std::ios::binary);
if (fin)
{
    unsigned char buf[64000];
    std::streamsize numRead;
    do
    {
        if (!fin.read(buf, 64000))
        {
            if (!fin.eof()) break;
        }
        numRead = fin.gcount();
        if (numRead < 1) break;
        // DO NOT send binary data using `LPTSTR` string conversions.
        // Binary data needs to be sent *as-is* instead.
        //
        SendFileContent(userKey, buf, numRead);
    }
    while (true);
}