【问题标题】:Need help using seekg在使用 seekg 时需要帮助
【发布时间】:2014-11-06 22:08:23
【问题描述】:

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

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

}

【问题讨论】:

  • 你有什么问题?
  • 那么问题是什么?
  • 如何从头到尾显示所有字符?反之亦然?
  • 首先,你为什么在一个不是以二进制模式打开的文件上使用seekg?由于回车/换行翻译,对以文本模式打开的文件使用 seekg 会让你发疯。
  • 我认为您将移动文件指针(从下一个读取的位置)与实际的读取操作(从当前位置读取并将文件指针增加读取的字节数)混淆了。

标签: c++ seekg


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-10-21
    • 2017-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多