Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ open a file as read-only

Tags:

c++

file-io

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)

like image 853
Dan1676 Avatar asked Dec 04 '22 06:12

Dan1676


1 Answers

The class ifstream is for reading only so, problem solved. Also, did you really mean to check argc after using argv[1] ?

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

fstream f;
f.open("file", fstream::in | fstream::out); /* Read-write. */
like image 50
cnicutar Avatar answered Dec 05 '22 20:12

cnicutar