gpt4 book ai didi

c++ - 一个关于fread的奇怪问题,offset与文档不符

转载 作者:行者123 更新时间:2023-12-02 18:39:11 24 4
gpt4 key购买 nike

//encrypt data
void EncryptBlock(unsigned char*& blockdata, size_t n)
{
}

//encrypt file
bool EncryptFile(const char* path, size_t blocksize)
{
FILE* fp = NULL;
auto erno = fopen_s(&fp, path, "rb+");
if (erno != 0)
{
printf("openfile:[%s] fail!!, errno=%d\n", path, erno);
return false;
}

//get file size
_fseeki64(fp, 0, SEEK_END);
int64_t filesize = _ftelli64(fp);
_fseeki64(fp, 0, SEEK_SET);
printf("filesize:%lld, %lldmb\n", filesize, filesize / (1024 * 1024));

int64_t processed = 0;
//buffer
unsigned char* blockdata = new unsigned char[blocksize];
while (1)
{
int64_t currpos = _ftelli64(fp);
//printf("curr:%lld, size=%lldmb\n", currpos, currpos / (1024 * 1024));

//read and set offset
size_t readsize = fread(blockdata, 1, blocksize, fp);
int64_t currpos2 = _ftelli64(fp);
if (currpos + readsize != currpos2)
{
return false;
}
_fseeki64(fp, -1 * readsize, SEEK_CUR);

//encrypt
EncryptBlock(blockdata, readsize);

//write
size_t writesize = fwrite(blockdata, 1, readsize, fp);
if (writesize != readsize)
{
printf("write:writesize=%llu, readsize=%llu, warning!!!!!!!!!!!\n", writesize, readsize);
}
processed += writesize;

if (readsize != blocksize)
{
printf("readsize=%llu, block=%llu, break[processd:%llu]\n", readsize, blocksize, processed);
break;
}
}
delete[] blockdata;
fclose(fp);

//error
if (processed != filesize)
{
printf("processed(%lld) != filesize(%lld), warning!!!!!!!!!!!\n", processed, filesize);
return false;
}
else
{
return true;
}
}
int main(int argc, char *argv[])
{
auto tv1 = GetTickCount64();
auto suc = EncryptFile("d:\\soft.msi", 1024 * 102);
auto tv2 = GetTickCount64();

auto used = (tv2 - tv1);
printf("encrypt:%s, cost:%llums\n", suc ? " succ" : " fail", used);
getchar();
return 0;
}

请使用大于20MB的文件

EncryptFile("path", 1024 * 1024) 或 EncryptFile("path", 1024 * 4) 正确

EncryptFile("path", 1024 * 102) 不正确

第二个周期将进入if (currpos + readsize != currpos2)

我使用windows10(vs2015)和Ubuntu20(gcc 9.3.0)也是同样的现象

https://i.loli.net/2021/07/08/Tdt4ocLsw9Mgn3R.gif

我想错误的原因应该是我对fread、fwrite和ftell的误解。 microsoft.docs.freadThe file pointer associated with stream (if there is one) is increased by the number of bytes actually read.

最佳答案

您需要在 fwritefread 之间使用 fseek

The standard says

output shall not be directly followed by input without an intervening call to the fflush function or to a file positioning function (fseek, fsetpos, or rewind), and input shall not be directly followed by output without an intervening call to a file positioning function, unless the input operation encounters end- of-file.

关于c++ - 一个关于fread的奇怪问题,offset与文档不符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68295406/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com