从std :: string vector返回char

时间:2014-11-23 05:28:19

标签: c++ string c++11 popen

你如何传递popen数据? 我有一个我使用的脚本但是当我尝试将数据带入另一个函数时,我得到转换错误 - >不推荐将字符串常量转换为'char *',因为popen希望使用标准字符。

代码:

#include <iostream>
#include <fstream>
#include <cstring>
#include <vector>

using namespace std;

FILE *init( char *fname ){
        FILE *fp = popen( fname, "r" );
        return fp;
}

char getmarketbuyData(FILE *fp){
        char buff[BUFSIZ];
        vector<std::string> vrecords;
        while(std::fgets(buff, sizeof buff, fp) != NULL){
                size_t n = std::strlen( buff );
                if ( n && buff[n-1] == '\n' ) buff[n-1] = '\0';
                if ( buff[0] != '\0' ) vrecords.push_back( buff );
        }
        for(int t = 0; t < vrecords.size(); ++t){
                cout << vrecords[t] << " " << endl;
        }
                return 0;
}

int main(void){
        FILE *fp = NULL;
        fp = init("/usr/bin/php getMyorders.php 155");
        if (fp == NULL) perror ("Error opening file");
        if ( fp )
                getmarketbuyData( fp );
}

错误:

#g ++ -g returnFileP.cpp -o returnFileP.o -std = gnu ++ 11 returnFileP.cpp:在函数'int main()'中: returnFileP.cpp:29:66:警告:不推荐将字符串常量转换为'char *'[-Wwrite-strings]

如何正确传递/返回popen数据到另一个函数?

1 个答案:

答案 0 :(得分:1)

init中呼叫main时收到错误消息。字符串文字"/usr/bin/php getMyorders.php 155"的类型为const char *,调用init需要隐式转换为char *。允许这种转换(对于字符串文字),但现在已弃用。

popen的第一个参数的类型为const char *,因此我没有看到为什么init需要非const参数的原因。将其声明为

FILE *init( const char *fname )

摆脱警告。

相关问题