C++打开文件只读

5

我编写了一个程序,它打开一个文件,然后逐行显示其内容(文本文件)

#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])中添加一些内容。)

OT: 不要使用 while(!infile.eof()),而应该使用 while(getline(infile,STRING)) - Bart
1
@Bart请详细说明。 - oddRaven
4个回答

15

ifstream只用于读取,因此问题解决了。此外,在使用argv [1]之后,您是否真的想检查argc

另一方面,当您使用fstream时,您需要指定文件的打开方式:

fstream f;
f.open("file", fstream::in | fstream::out); /* Read-write. */

2
ifstream类的open函数默认的模式参数是ios::in,意思是:
infile.open(argv[1]); 

等同于:

infile.open(argv[1], ios::in); 

所以您正在以只读模式打开文件。


1
你已经以只读模式打开了文件。如果你使用ifstream,就不能向它写入任何内容。
infile.rdbuf()->sputc('a');

注定会失败。


0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接