2014-11-23 66 views
0

如何传递popen数据? 我有一个我使用的脚本,但是当我尝试将数据带入另一个函数时,我得到一个转换错误 - >从字符串常量到'char *'的弃用转换,因为popen想要在标准char中。从std :: string向量返回char

代码:

#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 returnFileP.cpp -o returnFileP.o -std = GNU ++ 11 returnFileP.cpp:在函数“诠释main()的': returnFileP.cpp:29:66:warning:从字符串常量到'char *'的过时转换[-Wwrite-strings]

如何正确地将popen数据传递给另一个函数?

+2

如果你没有修改'fname',把它设为'const'。不要强迫该函数的用户解决缺乏const正确性的问题。 – chris 2014-11-23 05:29:21

回答

1

main中致电init时出现错误。字符串文字"/usr/bin/php getMyorders.php 155"的类型为const char *,并且对init的调用需要隐式转换为char *。这种转换(对于字符串文字)是允许的,但现在已被弃用。

popen的第一个参数的类型为const char *,所以我没有看到为什么init需要一个非const参数。声明它为

FILE *init(const char *fname) 

摆脱警告。

相关问题