c++fstream

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?


Solution

  • 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);
    }