在C ++中将变量(of char)传递给popen

时间:2015-04-08 02:07:11

标签: c++ popen

我正在尝试将一串字符从用户输入和grep命令传递给popen,以检索用户指示的指定文件夹中的第一个元素。

我环顾四周,但未能找到一个好例子。 这是我的代码;

FILE *fp = popen("grep -n ", term, " ", file_to_search, " | cut -f 1" );    
//  This is a note: <---- term (changing variable) and 
//  file_to_search (stagnant variable indicated by the user)
char buf[1024];

while (fgets(buf, 1024, fp)) {
    cout << buf << endl ;       // This is a note: <------- is this right to call the return info? 
}
fclose(fp);

2 个答案:

答案 0 :(得分:2)

您尝试使用popen与函数所期望的相差甚远。请参阅the man pages

您需要以下内容:

char command[1000]; // Make it large enough.
sprintf(command, "grep -n '%s' '%s' | cut -f 1", term, file_to_search);
//  Use of '' around term and file_to_search allows you to have 
//  whitespaces in them.

FILE *fp = popen(command, "r");
if ( fp == NULL )
{
    // Deal with error condition.
}

// Rest of your code.

答案 1 :(得分:0)

我最终编写了一个脚本来执行此操作,但仍然希望寻找并找到答案以启动并运行c ++版本。

int main () {

ifstream file ;
string line ;
string input, file_to_search ;

cout << "File you want to open in the directory: " ;
cin >> input ;

cout << endl << "File you want to search against: " ;
cin >> file_to_search ;

file.open( input.c_str()) ;
vector <string> file_content ;

if (file.is_open()) {

    while (getline(file, line)) {
        file_content.push_back(line) ;
    }

    vector <string> :: iterator p ;

    for (p = file_content.begin( ); p != file_content.end( ); p++) {
        cout << *p << endl ;

        string term = *p ;







        char command[10000000000000] ;
        sprintf(command, "grep -n '%s' '%s' | cut -f 1", term.c_str(), file_to_search.c_str()) ;

        FILE *fp = popen(command, "r") ;
        if (fp == NULL ) {
            cout << "Error. " << endl ;
        } else {
            cout << "Command output: " << fp << endl ;
        }


        /*
        char command[10000000000000000]; // Make it large enough.
        sprintf(command, "grep -n '%s' '%s' | cut -f 1", term, file_to_search);
        //  Use of '' around term and file_to_search allows you to have
        //  whitespaces in them.

        FILE *fp = popen(command, "r");
        if ( fp == NULL )
        {
            // Deal with error condition.
        }

        // Rest of your code.

        */










    }

    string program_abort ;
    cout << endl << endl << "Does the system input look right ( y or n): " << endl ;
    cin >> program_abort ;

    if ((program_abort == "yes") || (program_abort == "y") ) {

        cout << endl << "Program will continue. " << endl << endl ;

    } else if ((program_abort == "no") || (program_abort == "n") || (program_abort != "no") ) {

        cout << endl << "Program has closed. " << endl << endl ;

        return 0 ;
    }
    file.close();






}
return 0 ;

}