读取终端中的输出并将其与字符串进行比较

Read output in terminal and compare it with a string

本文关键字:字符串 比较 终端 输出 读取      更新时间:2023-10-16

如何检查像"fortune"这样的程序是否已经用程序安装?这是我的代码:

if(choice==1)
{
    cout<<"Need to Install program first? [y/n]: ?"<<endl;
    cin>>yn;
    if(yn=='y' || yn=='Y')
    {
            cout<<"Installing..."<<endl;
            cout<<"Enter password if asks:"<<endl;
            system(" sleep 2");
            system("sudo apt-get install fortune");

    }

我试过了,但没能得到我想要的。

dpkg-query -1W fortune  2>&1 |  read line ; do echo $line | say ; done

更新:我已经解决了这个问题,感谢@John Zwinck

如果你想知道是否安装了像fortune这样的程序,你可以简单地检查它是否存在!

if (access("/usr/bin/fortune", R_OK | X_OK) == 0)
    printf("we have good fortunen");

如果你有一个程序应该在$PATH的某个地方,但你不知道在哪里,你可以试着运行它:

if (system("fortune --help") != -1)
    printf("we have good fortunen");