does fstream read/write move file pointer

前端 未结 2 581
我在风中等你
我在风中等你 2021-01-12 22:55

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:

cpo         


        
相关标签:
2条回答
  • 2021-01-12 23:12

    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.

    0 讨论(0)
  • 2021-01-12 23:21

    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);
    }
    
    0 讨论(0)
提交回复
热议问题