Theocharis K.
Theocharis K.

Reputation: 1341

Open file to display content in C++

I have 2 questions to ask regarding opening files (any kind of files) using C++. I am currently working on a GUI program and I want to add a changelog in txt form. Also I want a menu in my program to open that changelog.txt with the default text editor every user has installed or to simply put it to open that text file. Please keep in mind that I want to open the file for display NOT in the program for input/output.I know I can do that using

system("notepad.exe filepath.txt");

or to open them with the preset program:

system("filepath.txt");

The problem is that both of those open a command line behind the notepad. I know there is another command to open files using Win32 API called CreateProccess() but my compiler doesn't recognise that command (OpenWatcom W32). So here are my questions:

1) Is there any other command to open files or is there a way to stop the command line from opening when using system command?

2) How do you define in Windows that the text file is in the current program folder? I mean instead of giving the entire filepath which will change from user to user is there any way to "tell" the program that the file is always on the current folder that the program is in?

I am sorry for any errors, if you want any clarification please let me know.

Upvotes: 3

Views: 4665

Answers (1)

David Heffernan
David Heffernan

Reputation: 612993

CreateProcess would be the wrong function to use here. That would require you to decide which process to run. The user may prefer to use a text editor other than Notepad, I know I do! The right way to do this on Windows is to ask the shell to open the file with whatever program the user has associated with the file. The ShellExecute function does this.

Call it like this:

ShellExecute(
    MainWindowHandle,
    "open",
    FullyQualifiedTextFileName,
    NULL,
    NULL,
    SW_SHOWNORMAL
);

You will need to include the Shellapi.h header file and link to the Shell32.lib library. If your compiler does not include these files, and I would be surprised if that was the case, then you can get them from the Platform SDK. That said, if you are serious about programming on Windows you should get hold of a tool that gives you access to the Windows API.

I do recommend that you use a fully qualified path for a task like this. Since your text file is located in the same directory as the executable you should simply join that directory to your text file's name. Get hold of the full path to the executable by calling GetModuleFileName passing NULL for the hModule parameter.

Upvotes: 5

Related Questions