Search code examples
c++stringfopen

Implicit file extension using fopen in C++


I'm working on a project where I'm required to take input from a file with an extension ".input". when run, the user gives the filename without the file extension as a command line argument. I then take that argument, argv[1] and open the file specified but I can't get it to work without the user typing in the entire filename

for example:

user enters> run file.input //"run" is the executable, "file.input" is the filename

user is supposed to enter> run file

how do I get this file extension implied when using this code:

fopen(argv[1],"r");

I tried using a string, setting it to argv[1] and then appending ".input" to it but fopen won't accept that string.


Solution

  • Without seeing your code, I can't say for certain what went wrong, but I suspect you did something like this:

    string filename = argv[1];
    filename += ".input";
    
    FILE* f = fopen(filename, "r"); // <--- Error here
    

    The issue here is that the C++ std::string type is not a char *, which is what's expected by fopen. To fix this, you can use the .c_str() member function of the std::string type, which gives back a null-terminated C-style string:

    FILE* f = fopen(filename.c_str(), "r"); // No more errors!
    

    As I mentioned in my comment, though, I think you'd be better off just using ifstream:

    string filename = argv[1];
    filename += ".input";
    ifstream input(filename);
    

    There's no longer a need for .c_str(), and you don't need to worry about leaking resources. Everything's managed for you. Plus, it's type-safe!