gpt4 book ai didi

c - 我的函数填充字符串值

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:03:39 24 4
gpt4 key购买 nike

我有以下功能

void runSysCall(char *command, char *output)
{

FILE *cmdline = popen(command, "rb");
size_t size = 0;


while(getdelim(&output, &size, 0, cmdline) != -1);

fclose(cmdline);
}

我从这个函数调用它,但我返回的是 null。

char * getVendorOfTheProcesses()
{

char * result = 0;
runSysCall("cat /proc/cpuinfo | grep -i 'Model'", result);

printf("%s", result);
return "asdsd";
}

如果您打印函数的结果值,它将给出它应该打印的结果。

如有任何帮助,我们将不胜感激。

最佳答案

请改变你的

FILE *cmdline = popen(command, "rb");

FILE *cmdline = popen(command, "r");

它有效(我测试了它 -- http://ideone.com/agV18s)。

来自 http://pubs.opengroup.org/onlinepubs/009696899/functions/popen.html

The mode argument to popen() is a string that specifies I/O mode:

If mode is r, when the child process is started, its file descriptor STDOUT_FILENO shall be the writable end of the pipe, and the file descriptor fileno(stream) in the calling process, where stream is the stream pointer returned by popen(), shall be the readable end of the pipe.

If mode is w, when the child process is started its file descriptor STDIN_FILENO shall be the readable end of the pipe, and the file descriptor fileno(stream) in the calling process, where stream is the stream pointer returned by popen(), shall be the writable end of the pipe.

If mode is any other value, the result is undefined.

似乎您使用 b 模式导致了问题(或出现未定义的行为)。

还要确保释放所有指针以避免内存泄漏。

另请注意,runSysCall 的每次迭代都会覆盖output。因此,在您的 getVendorOfTheProcesses 中,当您打印 result 时,您将得到 null,因为这是最后读取的内容。因此,您必须确保追加每一行并将其返回到 runSysCall 而不是使用 result

我稍微更改了您的代码以包含我的意思 -- http://ideone.com/QVTjiD这只是一个示例,您应该根据自己的需要对其进行调整并结合内存管理。

要验证您的代码是否正常工作(在我的机器上计数为 128,您的可能不同),您可以使用如下内容:

$ cat /proc/cpuinfo | grep -i 'Model' | wc -l
128
$ ./a.out | wc -l
128

希望对您有所帮助。

关于c - 我的函数填充字符串值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16549850/

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