如何从头到尾读取文本文件。 C++
Posted
技术标签:
【中文标题】如何从头到尾读取文本文件。 C++【英文标题】:How to read a text file from the beginning up to a certain point. C++ 【发布时间】:2020-04-12 18:56:25 【问题描述】:所以我正在为一个讨论随机访问文件的课程做一些工作。其中一个问题(选项 3)要求我们创建一个代码,该代码获取一个文本文件,并从头到尾读取并显示其内容(这将由用户给出)。在用户给出输入后,我将如何设置代码以停止阅读? 到目前为止,这是我的代码
#include <iostream>
#include <fstream>
#include <stdlib.h>
#include <string>
#include <iomanip>
using namespace std;
int main()
char filename[]="file.txt";
char content[10];
ifstream inFile;
int choice;
int option;
l1: cout << "Choose an option to decide what you want to do with the file." << endl;
cout << "Option 1: Beginning to End."<< endl;
cout << "Option 2: End to Beginning."<< endl;
cout << "Option 3: Beginning to Certain Point."<< endl;
cout << "Option 4: Certain Point to Certain Point. "<< endl;
cin >> choice;
if (choice==1)
inFile.open(filename);
if(inFile.fail())
cout << "file named can not be found \n";
system("pause");
exit(1);
inFile>>content;
while(inFile.good())
cout <<content<< ' ' <<endl;
inFile>>content;
inFile.close();
cout << "Do you want to go again? 1 for Yes and 2 for No."<< endl;
cin >> option;
if (option== 1)
goto l1;
else
terminate();
if (choice==2)
inFile.open(filename);
if(inFile.fail())
cout << "file named can not be found \n";
system("pause");
exit(1);
char c;
std::ifstream myFile(filename,std::ios::ate);
std::streampos size = myFile.tellg();
for(int i=1;i<=size;i++)
myFile.seekg(-i,std::ios::end);
myFile.get(c);
printf("%c",c);
cout << "Do you want to go again? 1 for Yes and 2 for No."<< endl;
cin >> option;
if (option== 1)
goto l1;
else
terminate();
if (choice==3)
inFile.open(filename);
if(inFile.fail())
cout << "file named can not be found \n";
system("pause");
exit(1);
【问题讨论】:
【参考方案1】:最简单的方法是获取他们想要停止读取的字符或行号并计数到该值。 类似的东西
int amount_read = 0;
int amount_to_be_read;
cin >> amount_to_be_read;
inFile>>content;
while(inFile.good() && amount_read < amount_to_be_read)
cout <<content<< ' ' <<endl;
inFile>>content;
amount_read++;
inFile.close();
【讨论】:
以上是关于如何从头到尾读取文本文件。 C++的主要内容,如果未能解决你的问题,请参考以下文章
C++文件读写操作如何统计文本的行数及如何读取文件某一行内容