fstream读/写移动文件指针 [英] does fstream read/write move file pointer

查看:470
本文介绍了fstream读/写移动文件指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个简单的问题,我希望可以很容易地回答,做文件流读取和写入操作移动指针吗?例如:

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

与逻辑上相同:

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

换句话说,carray []包含相同的内容(我不能看到第一个方法是有效的,所以我希望正确的答案是肯定的)。如果是这样,是写操作显示的相同行为?

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?

推荐答案

是的,这是它的工作方式。你的例子不一样,但。您的第一个示例读取从10000,然后10001,然后10002,等等。第二个需要循环外寻求设置初始位置。为了达到100%的等效性,你需要让你的第二个例子看起来像:

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

这篇关于fstream读/写移动文件指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆