gpt4 book ai didi

C++ pwrite() 偏移量

转载 作者:行者123 更新时间:2023-11-28 07:10:05 27 4
gpt4 key购买 nike

我正在寻找一个 C++ 程序来将一些模式写入磁盘设备,但是当我尝试设置大于 0 的偏移量时遇到了问题。请参见下面的示例和代码。

谁能告诉我我做错了什么?

谢谢,

root@solaris:~/# CC simple_test.cc
root@solaris:~/# ./a.out
Insert device name, for example: /dev/rdsk/c2t600A0B800011238000001D3D45DA78A7d0s1
/dev/rdsk/c0t6000402E5000000035969F0C97324D24d0s2
iteration: 0. offset: 0
offset: 1048577
iteration: 1. offset: 1048577
WRITE operation error: 22; offset: 1048577
offset: 2097154
iteration: 2. offset: 2097154
WRITE operation error: 22; offset: 2097154
offset: 3145731
iteration: 3. offset: 3145731
WRITE operation error: 22; offset: 3145731
offset: 4194308
iteration: 4. offset: 4194308
WRITE operation error: 22; offset: 4194308
offset: 5242885
Test completed
root@solaris:~/# cat simple_test.cc
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <sstream>

#define BS 1048576
using namespace std;
const char PATTERN[ ] = { 'A' };

int main(int argc, char **argv)
{
char dev[ 100 ];
printf( "Insert device name, for example: /dev/rdsk/c2t600A0B800011238000001D3D45DA78A7d0s1\n" );
scanf( "%s", dev );
int fd;
if ( ( fd = open( dev, O_RDWR ) ) == -1 )
{
printf( "error opening device: %s\n", dev );
return 1;
}

char* pattern = new char[ BS ];
memset ( pattern, PATTERN[0], BS );
int offset = 0;
int nbytes = 0;
for (int i=0; i<5; i++ ) {
cout << "iteration: " << i << ". offset: " << offset << endl;
nbytes = pwrite( fd, pattern, BS, offset );
if ( nbytes != BS )
printf( "WRITE operation error: %d; offset: %ld\n", errno, offset );
offset += BS + 1;
cout << "offset: " << offset << endl;
}

delete pattern;
printf( "Test completed\n" );
return 0;
}

最佳答案

我不确定,但是你不需要以 block 的形式写入 block 设备吗?所以你的偏移量必须是 block 大小的倍数。但是您将它增加 BS + 1。为什么是 +1?我认为如果您坚持使用 += BS,它可能会起作用。

关于C++ pwrite() 偏移量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21149793/

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