C -使用lseek()获得的read()位置不准确
C - Inaccurate read() position obtained with lseek()
创建一个文件,移动到位置128并写入数据,但是,在读取时,我需要从偏移量0而不是128读取它,尽管我在128中写入。谁能指出我哪里错了?
写入后,打印文件的十六进制。当我写入该页面时,数据应该打印在转储1(位置128)中。但是显示在转储0(位置0)。
从外部文件的Hexdump显示数据是我写入的位置(128)。
是否与模式或文件权限有关?我在linux系统上工作。
void readyCache() {
fd = open("database.dat",O_RDWR|O_TRUNC|O_CREAT , S_IRUSR|S_IWUSR);
}
char* getPage(long pageNumber, int fd) {
long offset;
char* buffer = (char *)malloc(pageSize);
offset = (pageNumber)*pageSize;
lseek(fd, offset+pageSize, SEEK_SET);
lseek(fd, offset, SEEK_SET);
read(fd, buffer, pageSize);
return buffer;
}
void setPage(long pageNumber,char* pageData, int fd) {
long offset;
offset = (pageNumber)*pageSize;
lseek(fd, offset, SEEK_SET);
write(fd, pageData, pageSize);
}
void hexdump(int fileDescriptor1, long pageNumber) {
cout << endl;
unsigned char readChar;
int iterator = 0, j = 0;
char * tempBuffer = (char *)malloc(pageSize);
tempBuffer = getPage(pageNumber, fileDescriptor1);
for(int i=0;i<pageSize;i++) {
readChar = tempBuffer[i];
iterator++;
j++;
printf("%02x ", readChar);//%02x
if (iterator == 16) {
iterator = 0;
cout<<endl;
}
}
}
int main() {
readyCache();
char * tempBuffer = getPage(1, fd);
int a = 1000;
memcpy(tempBuffer, &a, sizeof(int));
setPage(1,tempBuffer, fd);
cout<<"nDump 0n";
hexdump(fd, 0);
cout<<"nDump 1n";
hexdump(fd, 1);
close(fd);
return 0;
}
无论文件大小如何,您都可以查找可以存储在"off_t"数据类型中的任何位置(与上文Cris Dodd的答案相反)。
你真正的问题是你正在混合c++流IO (cout <<)使用C标准IO (printf)和POSIX底层IO (lseek)。他们互相混淆了!
如果你先转换成纯C语言(把cout的所有用法都改成printf),你的程序就能像预期的那样工作了。
c++标准定义了一个方法"sync_with_stdio(bool sync)",你可以用它来同步c++的iostreams和stdio。如果您不使用它,同步是未定义的。
相关文章:
- 将值指定给向量(2D)的向量中的某个位置
- 使用Unreal C++获取VR耳机的世界位置/方向
- 写入位置0x0000000C时发生访问冲突
- 如何将两个不同矢量的同一位置的两个元素组合在一起
- GL_SHADERSTORAGE_BUFFER位置是否与其他着色器位置冲突
- 如何使用cudaMallocManaged在指针位置初始化对象?(C++)
- 无法获取webot::PositionSensor对象中位置传感器的值
- 非常量变量只读位置的赋值
- 如何定义更改car类中car位置的方法
- 使用迭代器时如何访问对象在向量中的位置?
- 更改.cpp程序的输入文件中数据的位置会意外更改输出
- 求最大元素位置的分治算法
- 你好。。。id_public变量不应该给出结果为 81 和 86 吗?为什么它为两个派生类占用不同的内存位置?
- 为什么我的点没有在 OpenGL 中绘制鼠标所在的位置?
- 如何将元素添加到向量的字符串位置
- 如何选择在 csv 文件中输出的位置
- 无法打开 fstream C++文件,即使它与 .cpp 位于同一位置
- TCP套接字:传入数据在ack之后(离开TCP读取缓冲区)但在read()/recv()之前的位置
- 访问冲突读取位置fstream read
- C -使用lseek()获得的read()位置不准确