How do I open any file in C or C++` in its native application?

Posted on 2007-10-17
Last Modified: 2010-04-15
I want the user to type in the path of the file they want to open and have it run as if you double clicked it.  This is in windowsXP.

I know how to prompt the user and get the string they enter, but am having trouble with the opening part.  I have tried WinExec and CreateProcess which seems to work for opening a specific application but not for taking a variable to point to a specific file.

I would prefer the answer in C if it is possible. C++ if not.

Thank you

Question by:EMPHelpdesk
    LVL 13

    Accepted Solution

    The key API you need is FindExecutable, which takes a filename and folder and returns to you the fully qualified path of the executable that handles that extension.

    #include <windows.h>
    #include <stdlib.h>

    void main() {
       char associatedExecutable[_MAX_PATH];
       char myFile[] = "temp1.txt";
       char myFolder[] = "C:\\Scratch";
       char systemString[_MAX_PATH * 2]; // Very Crude!

       HINSTANCE h = FindExecutable(myFile,myFolder,associatedExecutable);
       // This is crude, but illustrates the point
       strcat(systemString," ");
    LVL 4

    Expert Comment

    The easiest way I've found is to use ShellExecute:

    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    6 Surprising Benefits of Threat Intelligence

    All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

    This article will show you some of the more useful Standard Template Library (STL) algorithms through the use of working examples.  You will learn about how these algorithms fit into the STL architecture, how they work with STL containers, and why t…
    Summary: This tutorial covers some basics of pointer, pointer arithmetic and function pointer. What is a pointer: A pointer is a variable which holds an address. This address might be address of another variable/address of devices/address of fu…
    The goal of the video will be to teach the user the difference and consequence of passing data by value vs passing data by reference in C++. An example of passing data by value as well as an example of passing data by reference will be be given. Bot…
    The viewer will learn how to pass data into a function in C++. This is one step further in using functions. Instead of only printing text onto the console, the function will be able to perform calculations with argumentents given by the user.

    759 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    12 Experts available now in Live!

    Get 1:1 Help Now