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函数给出一个偏移量,一个源和要写入的字节数 .
它首先检查文件是否能够打开, fseek
s到我想要的文件大小-1,然后写一个字节 . 然后在文件中 fseek
s给出偏移量 . 如果它成功写了 nbytes
,它打印出一些东西,然后关闭文件 . 否则它打印出它无法写入和关闭文件 .
在我的主要内容中,我有两个for循环,后面有两个写入 . 我之后也在做 test.read
,但我不确定为什么我应该在编译时进入调试模式 .
仅供参考, read
类函数几乎与 write
相同,但当然 fread
.
我的问题是:当我逐步使用调试模式时,为什么我没有得到结果,为什么我无法正确填充缓冲区 . 这是"almost"就像我的 write
s / read
并没有真正发生 .
EDIT: 我是"trying to do"填充了一个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); return - %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
1 回答
以下是我看到的问题:
你fopen the file with "wb",如果存在则截断文件,如果不存在则创建新文件 . 那么你怎么期望寻求20字节?
SIZE_OF_FILE设置在哪里或更重要的是它设置正确吗?
建议:永远不要忘记检查您正在呼叫的所有功能的返回代码 . 打印出来 . 就像你在这做的那样:
if (!pFile){ /*...*/}
例如 .
不要混淆,我刚刚展示了3种不同的方式来打印3个不同的调用的调试信息 . 你可以选择任何一种方式(最好是第三种方式)并随处使用 .