gpt4 book ai didi

c++ - 在 C++ 中函数 'FILE* popen()' 的参数太多

转载 作者:行者123 更新时间:2023-11-30 03:28:32 26 4
gpt4 key购买 nike

我写了一个小测试程序,当用 GCC 编译时,它可以按预期编译和运行:

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

#define BUFFSZ 512

int ping_test(char *host);

int main(void) {
if (ping_test("192.168.1.1"))
printf("PING OK!\n");
else
printf("PING FAIL!\n");



}

// returns 1 if ping succeeds, 0 otherwise
int ping_test(char *host)
{
FILE *in;
int i = 0;
int ok = 1;
extern FILE *popen();
char buff[BUFFSZ] = {0};
char res[BUFFSZ] = {0};
char cmd[50]={0};

sprintf(cmd,"ping -c 1 %s",host);
if(!(in = popen(cmd, "r"))){
exit(1);
}
while(fgets(buff, sizeof(buff), in)!=NULL){
strcat(res,buff);
}
pclose(in);
printf("RESULT: %s\n",res);
// check for string "100%"
for (i=0;i<BUFFSZ;i++) {
if (res[i] == '\%' &&
res[i-1] =='0' &&
res[i-2] =='0' &&
res[i-3] =='1'){
ok = 0;
return ok;
} else
ok = 1;
}
return ok;
}

现在我想在我正在处理的 Qt C++ 程序中使用这个相同的函数,所以我将该函数复制到我的类中的一个私有(private)方法中:

int JTFTestSuite::Ping(char *host)
{
FILE *in;
int i = 0;
int ok = 1;
extern FILE *popen();
char buff[BUFFSZ] = {0};
char res[BUFFSZ] = {0};
char cmd[BUFFSZ]={0};

sprintf(cmd,"ping -c 1 %s",host);
if(!(in = popen(cmd, "r"))){
exit(1);
}
while(fgets(buff, sizeof(buff), in)!=NULL){
strcat(res,buff);
}
pclose(in);
printf("RESULT: %s\n",res);
// check for string "100%"
for (i=0;i<BUFFSZ;i++) {
if (res[i] == '\%' &&
res[i-1] =='0' &&
res[i-2] =='0' &&
res[i-3] =='1'){
ok = 0;
return ok;
} else
ok = 1;
}
return ok;
}

header 中的声明:

private:
int Ping(char *host);

但是现在,它无法编译,编译器会提示:

error: too many arguments to function 'FILE* popen()'
if(!(in = popen(cmd, "r"))){
^

为什么我想知道这个?两个源文件中的包含是相同的

最佳答案

在 C 中,您可以通过使用空参数列表来声明函数而不声明任何特定原型(prototype)。 (你不应该这样做。它已经被弃用了很长时间。但你可以。)如果你想声明一个不带参数的函数,你需要使用 void作为参数列表。

这在 C++ 中不起作用。在 C++ 中,空参数列表意味着函数不接受任何参数。

所以在 C 中,

FILE* popen();  // unspecified what the parameters are
FILE* f = popen(cmd, "r"); // called with two strings

在 C++ 中

FILE* popen();  // takes no arguments
FILE* f = popen(cmd, "r"); // illegal because popen takes no argument.

而不是声明 popen (和其他库函数)你自己,#include正确的头文件。 popenpclose<stdio.h> , 但您需要确保定义正确的 feature test macro在任何 #include 之前秒。 (例如,#define _XOPEN_SOURCE 700 将起作用。)

关于c++ - 在 C++ 中函数 'FILE* popen()' 的参数太多,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46517288/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com