需要帮助使用seekg

时间:2014-11-06 22:08:23

标签: c++ seekg

我需要编写一个程序来读取文件中的某些字符。 例如:从开始到结束或以相反顺序排列的所有字符。如何显示所有字符而不是一个?

//This program reads a file from beg to end, end to beg, beg to 4th position,
//8th to 15th position, end to 3rd position, and 22nd to end

#include <iostream>
#include <fstream>

using namespace std;

int main()
{
char letter; //holds the character

fstream file("alphabet.txt", ios::in);

file.seekg(5L, ios::beg); 
file.get(letter);
cout << "Beginning to the 4th letter: " << letter << endl;

file.seekg(-22L, ios::end); 
file.get(letter);
cout << "21st letter to the end: " << letter << endl;

file.close();
system("pause");
return 0;

}

1 个答案:

答案 0 :(得分:0)

蛮力方法是使用循环来读取文件中的所有字符,从字体到后面:

char c;
while (my_file >> c)
{
  // Do some stuff
}

无需调整文件位置指针,因为读取功能会根据读取的字符数自动推进文件位置。很酷的功能!

从后到前阅读文件是您和操作系统的浪费时间和精力。所有内容都经过优化,可以从前到后阅读,因此您将不受影响。

算法将是:

Open file in binary (to avoid translations)  
Seek to the end position less one.  
Save the position.  
While file position is not at beginning do:  
    Decrement your position variable.
    Seek to the position.
    Read a character
    Process character
    End-While

一种更好的方法来反转文件中字符的排序是将整个文件读入内存,然后以相反的顺序将内存写入新文件。这里的问题是你的程序是否有足够的内存来读取整个文件。