简体   繁体   English

如何复制ifstream的状态?

[英]How can I copy the state of an ifstream?

I have a function that takes an ifstream, ifs, and uses it to fill this: std::vector< std::vector > matrix; 我有一个函数,它接受一个ifstream,ifs并用它来填充:std :: vector <std :: vector> matrix; (this is an assignment and I do not have any say in how to better implement this). (这是一项任务,对于如何更好地实现这一点,我没有任何发言权)。 I would like to know length of the file I am reading before I begin filling "matrix" This way, I will avoid constantly resizing. 在开始填充“矩阵”之前,我想知道正在读取的文件长度,这样可以避免不断调整大小。 However, I only have one ifstream object, ifs. 但是,我只有一个ifstream对象ifs。 If I use a loop to find the length of the file, I will be at the end of the file and I am unsure how to 'refresh' an ifstream so that it is at the first line again. 如果使用循环查找文件的长度,则将位于文件末尾,并且不确定如何“刷新” ifstream,使其再次位于第一行。 Something else I was considering was creating a copy of ifs. 我正在考虑的其他事情是创建ifs的副本。 This way, I can loop through one ifstream, close it, and use the other one to fetch the data. 这样,我可以遍历一个ifstream,将其关闭,然后使用另一个来获取数据。 I feel like there would be an issue having two ifstreams open and pointed at the same file. 我觉得打开两个ifstream并指向同一个文件会出现问题。

I do not know of a way to implement either idea. 我不知道实现任何一个想法的方法。 Please assume that I can no longer access the original file name/path. 请假设我无法再访问原始文件名/路径。

Any ideas? 有任何想法吗?

Don't try to copy streams. 不要尝试复制流。
To jump to the beginning, just use seekg : 要跳到开头,只需使用seekg

ifs.seekg(0);

If you reached the end of the stream before seeking, another problem is that the stream remembers the file end internally and seekg doesn't reset this. 如果在查找之前已到达流的末尾,则另一个问题是流会在内部记住文件的末尾,而seekg不会重置该文件。 For this to work, use 为此,请使用

ifs.clear();

before seeking. 在寻求之前。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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