Opening file using Argc and Argv

I have a folder containing a .txt file with one line sentence. And in the same folder i have my .cpp file to open the .txt file and print the message to the screen. But my issue is I keep getting the message that no file name was entered.

How can I fix this issue? What am I doing wrong? And lastly is it possible to open and print more than file with the command line? if so how?

Here is my code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <fstream> // for file-access
#include <string>
#include <iostream>
using namespace std; 
int main(int argc, char* argv[])
{ 
    if (argc > 1) {
        cout << "argv[1] = " << argv[1] << endl; 
    } else {
        cout << "No file name entered. Exiting...";
        return -1;
    }
    ifstream infile(argv[1]); //open the file
    
    if (infile.is_open() && infile.good()) {
        cout << "File is now open!\nContains:\n";
        string line = "";
        while (getline(infile, line)){
            cout << line << '\n';
        }
        
    } else {
        cout << "Failed to open file..";
    }
    return 0;
}
Last edited on
But my issue is I keep getting the message that no file name was entered.

That would appear to mean you didn't supply the name of the file which you want to be opened.

By the way, there's an extraneous cin at line 8, other than that your code looks ok. The problem is in how you are running it.
is it possible to open and print more than file with the command line

You could supply each filename as another parameter on the command line. Then check argv[2], argv[3] and so on - depending on the value of argc of course.
Last edited on
How should i supply the name of the file? Can I do it within the program?
Last edited on
C++ is a compiled language. You start with the source code in a .cpp file. When it is compiled and linked, the end result is an executable program, on windows systems that will be a .exe file.

You run that exe file from the command line by typing its name, followed by any parameters, in this case the parameter is the name of the file you want to open.

Can I do it within the program?

Yes. But that would be a change of direction.

The opening post refers to using the command line. The program code gets the parameter from the command line. You could discard that part of the code which refers to argc and argv completely, and instead either type the actual filename as a string in the program code, or prompt the user (with a cout message) and then get the filename as input using cin.
Last edited on
Topic archived. No new replies allowed.