【问题标题】:Set start and finish limits to read from file设置从文件读取的开始和结束限制
【发布时间】:2018-05-05 02:21:54
【问题描述】:

我需要从 txt 文件中读取数据。我需要的数据从文件中的某个位置开始,到另一个位置结束(不是最后)。我知道如何更改开始位置 (fin.seekg(startPos);),但是如何设置我的结束位置? 我有一个限制数字,比如说从开始的 100 个位置开始读取,从结束的 30 个位置停止。

【问题讨论】:

  • 如果您知道结束位置,则从中减去开始位置,并且从文件中读取的字符数不超过该字符数。任务完成。

标签: c++ file io position


【解决方案1】:

你可以像这样使用 fin.tellg:

fin.seekg(0, fin.end);
length = fin.tellg();

计算文件中“位置”的总数。然后转到所需的起始位置并获取输入,直到位置数减 30。完整示例:

int startPos = 100, length;
string input;
ifstream fin("file.txt");

fin.seekg(0, fin.end);
length = fin.tellg();
fin.seekg(startPos);

for (int i = startPos; i <= length - 30; i++) {
    getline(fin, input, '\n')
    //do something with 'input'
}

fin.close();

【讨论】:

  • 没问题!编码愉快!
猜你喜欢
  • 2018-02-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多