无符号长整数不包含有效值

时间:2013-04-02 13:28:29

标签: c++

我的问题是我觉得非常奇怪。 事实上,我列出了给定流程的所有子流程。

为此,我使用:How to find all child processes?和RC的答案。

但是,我需要一个带有unsigned long的出口。 解决方案根据char[]

提供一些字符串

如果我想获得unsigned long,我需要修改代码才能获得数值。另一种情况不正确。

所以我将char设为unsigned long。然后,scanf带有%ld代码。

但我得到了废话......

为什么这不起作用?

编辑:代码:

const char *name = "top";
char command[100];
unsigned long parentID; unsigned long processID;

strcpy(command, "ps -C "); strcat(command, name); strcat(command, " --format '%P %p'");

FILE *fp = popen(command, "r");
    if (fp == NULL) fprintf(stderr, "Error in reading PID child processes information !\n");

while(fscanf(fp, "%lu %lu", parentID, processID) != EOF) {
    printf("PID : %lu Parent : %lu \n", processID, parentID);
}

return processID;

使用,%schar[256],这项工作!

编辑:Toughts

我在考虑两种方法:

  • 首先,使用unsigned long代替char[]
  • 其次,在阅读文件后将char[]转换为unsigned long。但是,我需要逐行阅读。可以使用popen吗?

1 个答案:

答案 0 :(得分:1)

  

所以我将char设为unsigned long。然后,scanf()带有%ld代码。

此处,您的程序会调用未定义的行为,因为unsigned long的类型说明符为%lu

(可能在您的代码中还有一些其他的,我们不可告诉的错误;将返回值从char *更改为unsigned long只是微不足道。)< / p>