简体   繁体   中英

Opening c++ program by double clicking associated file. How do I get the file name?

I have a c++ program that I associated with .bin files, so that whenever the .bin file is opened, it is opened with myProgram.exe.

How do I get the filename of the associated file that opened my program?

The process of opening a file via its extension is controlled by a set of entries in the system registry. One of the final steps specifies the command that should be executed, and usually the file name is included in the command. Check your command line parameters to see if the file name is given.

The process is described here: http://msdn.microsoft.com/en-us/library/cc144175(v=vs.85).aspx

IIRC, it will be the second command line parameter passed into your application. The first parameter will the name of your actual program (executable).

In plain C++ you can use the arguments of main :

#include <iostream>
int main( int argc, char* argv[] )
{
    using namespace std;
    cout << argc << " arguments:" << endl;
    for( int i = 0;  i < argc;  ++i )
    {
        cout << "[" << argv[i] << "]" << endl;
    }
}

But there is a problem with that , namely that C and C++ main was designed for *nix, not Windows. The Holy C++ Standard recommends that the runtime should supply the main arguments UTF-8-encoded, but alas, that does not happen with conventional Windows C++ compilers. So in Windows this method might not work for filenames with eg Norwegian, Greek or Russian characters.

In Windows, for a program intended to be used by others you can instead use the (Unicode version of the) Windows API function GetCommandLine , and its parser cousin CommandLineToArgvW in order to split the command line into individual arguments.

Alternatively, with Microsoft's implementations of the C and C++ languages you can use the non-standard startup function wmain . I don't recommend that, however. I think it is a good idea to keep to the international standards for C and C++ as much as practically possible, and there is certainly no pressing reason to use wmain , even though it can be convenient for small toy programs.

Cheers & hth.,

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM