C -使用lseek()获得的read()位置不准确

C - Inaccurate read() position obtained with lseek()

本文关键字:read 位置 不准确 lseek 使用      更新时间:2023-10-16

创建一个文件,移动到位置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。如果您不使用它,同步是未定义的。