在我的C ++程序中打开Microsoft Word

时间:2015-06-01 00:00:05

标签: c++ macos

正如标题所提到的,我试图通过这个程序打开Microsoft Word并遇到一些困难。在对流程进行了一些研究之后,我决定通过使用Process ID和Fork函数来处理在我的程序中打开另一个文件。我似乎遇到一些困难的地方是exec家庭功能。它们似乎是这些功能的各种不同用途,但我很难绕过哪些功能我应该使用这个功能以及我是否在合理地正确地布置我的论点。

当我输入" msword"时,我的控制台会将以下内容打印到屏幕上:

你好---,你想打开什么应用程序?

MSWORD

创建子进程以打开Microsoft Word

父流程

打开Microsoft Word

#include <stdio.h>
#include <iostream>
#include <string>

// Routine Headers
#include <sys/types.h>
#include <unistd.h>
using namespace std;

//function that actually processes loading the program, will take the result of searchApplication
void loadApplication(string path)
{
    // If the user typs Microsoft Word (msword abbreviation...)
    if(path == "msword")
    {
        cout << "Creating Child Process To Open Microsoft Word\n";
        pid_t ProcessID = fork();

        if(ProcessID == -1)
        {
        cout << "Error creating another Process... Exiting\n";
        exit(1);
        }
        // This is the child process
        else if (ProcessID == 0)
        {
            execle("/Applications/Microsoft Office 2011", nullptr);
        }
        // This is the parent process
        else
        {
            cout << "parent process\n";
        }
    }

int main()
{
    cout << "Hello ---, what application would you like to open?\n";
    string input;
    cin >> input;
    loadApplication(input);


    return 0;
}

1 个答案:

答案 0 :(得分:-1)

你不必为此使用fork / exec。只需将open命令传递给system()

即可
#include <cstdlib>

int main() {
   system("open /Applications/App\\ Store.app");
   return 0;
}

请注意,您需要转义应用程序名称中的任何空格(如上所示),并指定全名(而不仅仅是显示的名称)。

这里非常closely related question