VidX
VidX

Reputation: 11

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

Creating a file, moving to location 128 and writing data but, while reading i need to read it from offset 0 rather than 128 though i am writing in 128. Can someone please point out where i am going wrong.

After writing, printing the hex of the file. the data should be printed in dump 1 (location 128) as I am writing to that page. But it is displayed in dump 0 (location 0).

Hexdump of the file from outside shows the data to be the location that i have written to (128).

Is it something to do with modes or file permissions? I am working on linux os.

    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 0\n";
            hexdump(fd, 0);
            cout<<"\nDump 1\n";
            hexdump(fd, 1);
            close(fd);
            return 0;
    }

Upvotes: 0

Views: 682

Answers (1)

NickStoughton
NickStoughton

Reputation: 721

You can always seek to any position that can be stored in a "off_t" data type, regardless of the file size (contrary to the answer from Cris Dodd above).

Your real problem is that you are mixing the C++ stream IO (cout << endl etc) with C standard IO (printf) and POSIX underlying IO (lseek). They are confusing each other!

If you first convert to pure C (change all of the uses of cout to printf) your program works as expected.

The C++ standard defines a method "sync_with_stdio(bool sync)" that you can use to synchronize C++ iostreams with stdio. If you don't use it, the synchronization is undefined.

Upvotes: 1

Related Questions