-1

我需要编写一个程序来读取文件中的某些字符。例如:所有字符从头到尾或倒序排列。如何显示所有字符而不是一个字符?

//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;

}
4

1 回答 1

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

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

于 2014-11-06T23:20:51.293 回答