【发布时间】: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);
}
}
}
【问题讨论】:
标签: c++ random-access randomaccessfile