2014-11-06 103 views
-1

我需要編寫一個程序來讀取文件中的某些字符。例如:從開始到結束或以相反順序的所有字符。我怎樣才能顯示所有的角色而不是一個?使用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; 

} 
+0

你的問題是什麼? – michaelc35 2014-11-06 22:10:54

+1

那麼問題是什麼? – PaulMcKenzie 2014-11-06 22:11:26

+0

如何顯示從頭到尾的所有字符?反之亦然? – anonymous1126 2014-11-06 22:13:54

回答

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 

更好的方法來扭轉字符的順序在一個文件是讀取整個文件到存儲器中,然後寫入存儲器,以相反的順序一個新文件。這裏的問題是你的程序是否有足夠的內存來讀取整個文件。