does fstream read/write move file pointer

拜拜、爱过 提交于 2019-12-30 09:36:10

问题


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?


回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/14148238/does-fstream-read-write-move-file-pointer

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!