我写了一个程序,它打开一个文件然后逐行显示它的内容(文本文件)
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main (int argc, char* argv[])
{
string STRING;
ifstream infile;
infile.open(argv[1]);
if (argc != 2)
{
cout << "ERROR.\n";
return 1;
}
if(infile.fail())
{
cout << "ERROR.\n";
return 1;
}
else
{
while(!infile.eof())
{
getline(infile,STRING);
cout<<STRING + "\n";
}
infile.close();
return 0;
}
}
我需要添加什么才能使文件只读?
(infile.open(argv[1])
是我猜测的地方)
最佳答案
ifstream
类仅供阅读,问题已解决。另外,您真的是想使用 argv[1]
检查 argc
after 吗?
另一方面,当您使用 fstream
时,您需要指定打开文件的方式:
fstream f;
f.open("file", fstream::in | fstream::out); /* Read-write. */
关于C++以只读方式打开文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8255935/