【发布时间】:2011-10-15 16:35:52
【问题描述】:
bool CReadWrite::write(unsigned long long offset, void* pvsrc, unsigned long long nbytes)
{ int m_WriteResult;
pFile = fopen("E:\\myfile.bin","wb");
if (!pFile){
puts("Can't open file");
return false;
}
fseek(pFile,SIZE_OF_FILE-1,SEEK_SET);
fwrite(pvsrc,1,1,pFile);
fseek(pFile,offset,SEEK_SET);
printf("fseek(pFile,SIZE_OF_FILE-1,SEEK_SET); returned -- ", fseek(pFile,SIZE_OF_FILE-1,SEEK_SET));
printf( "fwrite(pvsrc,1,1,pFile); returned -- %d", fwrite(pvsrc,1,1,pFile));
printf("Current file pointer position is : %d\n",ftell(pFile));
m_WriteResult = fwrite (pvsrc, 1, nbytes, pFile);
if (m_WriteResult == nbytes){
puts("Wrote to file");
printf("The number of bytes written to the file is : %d\n\n",m_WriteResult);
fclose(pFile);
return true;
}
else{
puts("Unable to write to File.");
fclose(pFile);
return false;
}
}
main.cpp:
char* pWriteBuffer;
char* pReadBuffer;
int nbytes = 85;
int nbytes2= 10;
pWriteBuffer = new char [nbytes];
pReadBuffer = new char [nbytes];
CReadWrite test;
for(Bufferndx = 0; Bufferndx<nbytes; Bufferndx++){
pWriteBuffer[Bufferndx] = Bufferndx;
}
test.write(20,pWriteBuffer,50);
for(Bufferndx = 10; Bufferndx;Bufferndx--){
pWriteBuffer[Bufferndx] = Bufferndx;
}
test.write(30,pWriteBuffer,nbytes2);
test.read(5,pReadBuffer,85);
delete[] pWriteBuffer;
delete[] pReadBuffer;
这是我的程序的一部分,它写入给定的缓冲区。 write 函数有一个偏移量、一个源以及要写入的字节数。
它首先检查文件是否能够打开,fseeks 到我想要的文件大小 -1,然后写入一个字节。然后它在文件中的fseeks 到给定的偏移量。如果它成功写入nbytes,它会打印出一些东西,然后关闭文件。否则它会打印出它无法写入并关闭文件。
在我的 main 中,我只是在测试我的代码是否真的写了我想要的,并且我有两个 for 循环,之后有两个写。在此之后我也在做test.read,但我不确定为什么我看不到正确的结果,我认为我应该在编译时进入调试模式。
仅供参考,read 类函数几乎与 write 相同,但当然是 fread。
我的问题是:为什么我在逐步使用调试模式时没有得到结果,为什么我看不到缓冲区被正确填充。这“几乎”就像我的writes/read 并没有真正发生一样。
编辑:我“试图做的”是用 85 个字节填充一个缓冲区(我最大的缓冲区)。
- 我的
test.write(20,pWriteBuffer,50)将从偏移量 20 开始并写入 50 个字节,也就是。偏移 20 -70。 - 我的第二次写入
test.write(30,pWriteBuffer,nbytes2)将从偏移量 30 开始并写入 10 个字节,也就是。偏移 20-30。 - 第三,我阅读了整篇文章,我应该能够分辨出所有写入发生的位置。
或者那是计划,但我在调试时没有看到。另外,也许有人可以对此有所了解,但我正在审查它,看起来我......
fseek(pFile,SIZE_OF_FILE-1,SEEK_SET);
fwrite(pvsrc,1,1,pFile);
每次我写的都是错误的……我不应该每次写都去寻找文件并把文件变大。呃
printf("fwrite(pvsrc,1,1,pFile); 返回 -- %d", fwrite(pvsrc,1,1,pFile)); //打印出1
printf("fseek(pFile,SIZE_OF_FILE-1,SEEK_SET); 返回 -- ", fseek(pFile,SIZE_OF_FILE-1,SEEK_SET)); //打印出0
【问题讨论】:
-
“为什么我在使用调试模式时没有得到结果”这是否意味着在不使用调试步骤时你确实得到了正确的结果?跨度>
-
你得到了什么?你期望得到什么?