c++filenotepad

How can I open up a file on the screen c++


So I have made a program that handles occupant records in a building. Most of the code s unrelated to my question except for one function, which is to write all the records of the occupants in this building to a printout file in .txt format.

Should I want to access this file on my Windows laptop, I would have to:

  1. Open up File Explorer
  2. search up the file in the search box

Now, what I want to do is to open up the file on the screen so that the user does not have to look it up on file explorer. I tried looking this up on the Internet, but every search of mine was confusing with fstream method of opening a file.

Again, just to avoid any confusion, my question is: Is there any library, function, or piece of code that will allow me to display a .txt file on the computer screen so that the user can avoid looking it up on file explorer (like open up this file on notepad)? This question is not anywhere, and I'm not sure how what level of difficulty this task would be.

If it helps, here is my code where I write to the file:

    ofstream print_file;
    print_file.open("PrintOut.txt"); // All records written to this file
    for (int i = 0; i < 57; i++) // Exactly 57 records
    {
        // Here I'm just writing each field of the occupant record in a formatted method to the file.
        print_file << "\nRecord for occupant in appartment number " << Occupant::occupant_apartments[i] << ":\n";
        print_file << "\tOccupant Name:       " << this->occupant_name[i] << endl;

        print_file << "\tLeasing Rights:     ";
        if (this->occupant_leased[i] == "Yes")
            print_file << " Authorized" << endl;
        else if (this->occupant_leased[i] == "No")
            print_file << " Unauthorized" << endl;
        else
            print_file << " Empty Appartment" << endl;

        print_file << "\tParking Issued:     " << this->occupant_parking[i] << endl;
    }
    // Here I'd like to add the code (or make my own code) that will be able to open up Notepad to display the file PrintOut.txt
}

Any input or suggestions will be greatly appreciated. If you need any more information or clarification about my question, please inform me in the comments.


Solution

  • Since you're on Windows, you could use the ShellExecuteW function to do that:

    #include <Windows.h>
    #pragma comment(lib, "shell32.lib)
    ...
    ShellExecuteW(NULL, L"open", L"C:\\path\\to\\my\\file.txt", NULL, L"C:\\path\\to\\my\\", SW_SHOW);