开发者

Problem with seekp(), seekg(), read() and write() on the same file

I'm dealing with a problem with files in C++ I'm not able to work out. I'm managing a file with registers and I'm trying to do "Sorted Insert", in Spanish is "Insercción ordenada" but I don't know the translation to English. What I try to do is opening the file at the end of it and comparing the register with the one I want to insert in the file. Each register greater than the new is moved one register's position to the end of file. I write the new register in its correct position when the comparison returns that the new is smaller than the current selected.

My concrete problem is the last register in the file is read 2 times and because of it, the register is written 2 times.

I'd like copy the code I've written but the names are in Spanish and the code contains lots of snippets to manage errors and conversions between char*s and structs... It's a mess and it only gets confuse us.

I think someone would have been in the same situation, I will thank examples on the web or some articles about how to use seekp and seekg on the same file.

Thanks a lot!

More or less the code:

int readPosition, writePosition;

readPosition = // Byte where the last register starts in the file.
writePosition = readPosition + registerSize;

f->seekg(readPosition,ios::beg);

oldReg = new char[registerSize];
f->read(oldReg,registerSize);
f->seekp(writePosition,ios::beg);

while () { // if cadena < new register
             // For writing, I need to move the reading pointer after the writing pointer
    f->seekg(readPosition + 2*registerSize,ios::beg);
        f->write(oldReg,registerSize);

        readPosition -= registerSize;
    writePosition -= registerSize;

        f->seekg(readPosition,ios::beg);
        f->seekp(writePosition,ios::beg);

                 delete oldReg;
                 oldReg = new char[r开发者_JAVA技巧egisterSize];

        f->read(oldReg,registerSize); 
    }

delete oldReg;

f->seekp(writePosition,ios::beg);
f->seekg(writePosition + registerSize,ios::beg);

f->write(newRegister,registerSize);

This is not the real code but what my method does. I want you notice how I use seekp() and seekg() because I am not sure about the way I use them. I've had several problems with seekp and seekg and I've noticed that the two pointers are very matched.


This doesn't work

f->seekg(readPosition,ios::beg);
f->seekp(writePosition,ios::beg);

A file only has one position. You have to do your seeks when you need them, when changing from reading to writing or vice versa.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜