简体   繁体   中英

does fstream read/write move file pointer

This is kind of a simple question that I hope can be answered easily, do the file stream read and write operations move the pointer along? As an example:

cpos=10000;
for (i=0;i<20;i++) {
   dataFile.seekg(cpos+i,ios::beg);
   dataFile.read(carray[i],1);
}

Is it identical (logically) to:

dataFile.seekg(cpos,ios::beg);    
cpos=10000;
for (i=0;i<20;i++) {
    dataFile.read(carray[i],1);
}

In other words, does carray[] contain the same contents regardless of which method is used (I can't see the first method being efficient so I am hoping that the correct answer is yes). If so, is same behavior exhibited by write operations?

Yes, that is the way it works. Your examples aren't quite the same, though. Your first example reads from 10000, then 10001, then 10002, etc. The second needs a seek outside the loop to set the initial position. To be 100% equivalent, you need to have your second example look like:

cpos=10000;
dataFile.seekg(cpos,ios::beg);
for (i=0;i<20;i++) {
   dataFile.read(carray[i],1);
}

Yes, the file pointer is automatically moved by read and write operations. ...and not seeking improves the performance a lot . Also, using file.read(ptr, 20) is a lot faster than using 20 times file.read(ptr + i, 1) . To get the same semantics, you'll need to navigate to the appropriate location, though, using one seek.

Seeking in a file stream sets the stream into a state where it can continue to both read or write characters: To switch between reading and writing for a stream opened in read/write mode ( std::ios_base::in | std::ios_base::out ) it is necessary to introduce a seek. Each see, thus, set the available buffer up in a funny way which the stream doesn't need to do if it just reads or writes a sequence of characters. Also, when writing each seek at least checks whether it is necessary to write characters to get into an initial state for code conversion.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM