-1

Suppose you want to allow the user to specify a file to open on the command line. How can this be achieved if the user will enter data such as:

/User/desktop/input.txt

How can I then convert this directory into something that the program actually opens/reads?

user3064097
  • 161
  • 1
  • 10
  • 1
    Y do you need the file name alone? The whole path is needed to open that particular file.. – Aswin Murugesh Dec 05 '13 at 08:28
  • 2
    Why would you need to split the path ? If you use just the filename and not the path how will you guarantee you know the directory ? – Johan Dec 05 '13 at 08:28
  • That's correct. I will modify my original question. – user3064097 Dec 05 '13 at 08:30
  • It's kind of unclear what do you mean by 'specifies on the command line'. Did you just mentioned command line, because you're building a console application or do you want to pass the filename/path on command-line to your program? – Constantin Dec 05 '13 at 08:43

4 Answers4

1

The parameter argc holds the count of command line arguments. If you don't pass any arguments, it's 1 (argv[0] is just the name of your executable). Otherwise its the count of command line arguments + 1.

#include <fstream>

int main (int argc, char **argv){
  if(argc>1){
    std::ifstream a(argv[1]); // first argument
    if(a){
      //file opened
    }
  }
}

To start this program, you would type on your command-line:

nameOfYourExecutable.exe /User/desktop/input.txt

See also here for further informations.

Community
  • 1
  • 1
Constantin
  • 8,721
  • 13
  • 75
  • 126
1

std::ifstream is the way.

std::ifstream file(your_file_path);

if (!file) { return; } // check the file 

std::string line;
while (getline(file, line)) { /* do some process on line */ }
Johan
  • 3,728
  • 16
  • 25
0

Just open("path",permissions,flags) will work fine.. and you can read or write using the file descriptor.

Aswin Murugesh
  • 10,831
  • 10
  • 40
  • 69
0

What is the deference if you get it from the command line argument, or hard-code it in your program? just use open().

yosim
  • 503
  • 2
  • 8