C++以只读方式打开文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8255935/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 18:16:09  来源:igfitidea点击:

C++ open a file as read-only

c++file-io

提问by Dan1676

I have written a program which opens a file then displays line by line its contents (text file)

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

#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; 
    }
}

What do I need to add to make the file be read only ?

我需要添加什么才能使文件只读?

(infile.open(argv[1])is where am guessing something goes)

(这infile.open(argv[1])是我猜测某事发生的地方)

回答by cnicutar

The class ifstreamis for reading only so, problem solved. Also, did you really mean to check argcafterusing argv[1]?

该课程ifstream仅供阅读,问题已解决。另外,你真的想argc使用检查argv[1]吗?

On the other hand, when you use fstreamyou need to specify how you want to open the file:

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

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

回答by codaddict

The default modeparameter of openfor ifstreamclass is ios::in. That is

for class的默认模式参数是. 那是openifstreamios::in

infile.open(argv[1]); 

is same as:

与:

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

So you are opening the file in read-only mode.

因此,您以只读模式打开文件。

回答by ybungalobill

You already open the file for read-only. Your can't write to it if you use ifstream. Even:

您已经以只读方式打开文件。如果您使用ifstream. 甚至:

infile.rdbuf()->sputc('a');

is guaranteed to fail.

保证失败。

回答by Christian

You don't need to do anything as the default value for the openmode is already ios_base::in. So you're already good to go :) See here for more details: http://en.cppreference.com/w/cpp/io/basic_ifstream/open

您不需要做任何事情,因为 openmode 的默认值已经是ios_base::in。所以你已经很高兴了 :) 有关更多详细信息,请参见此处:http: //en.cppreference.com/w/cpp/io/basic_ifstream/open