开发者

fscanf returns (null)

开发者 https://www.devze.com 2023-03-31 08:54 出处:网络
When running the following code: FILE *input; char *name=NULL,*stat=NULL; int i=0,j=0; input=fopen(\"/proc/1/stat\",\"r\");

When running the following code:

FILE *input;
char *name=NULL,*stat=NULL;
int i=0,j=0;
input=fopen("/proc/1/stat","r");
fscanf(input,"%d",&i);
fscanf(input,"%s",name);
fscanf(input,"%s",stat);
fscanf(input,"%d",&j);
printf("pid : %d name: %s status: %s ppid: %d",i,name,stat,j);

I get the output:

pid : 1 name: (null) status: (null) ppid: 0

The content of /proc/1/stat 开发者_JAVA技巧is

1 (init) S 0

Can you please tell me what i did wrong here?


You need to initialize both name and stat either with a malloc or

char name[LENGTH];

if you just write

char *name;

It wouldn't work


name and stat must NOT be NULL... you must initialize them - by defining them directly as an array like char name [LENGTH]...


I run your code and it works.

FILE *input;
input = fopen("stat","r");

int i, j;
char name[100], stat[100];

fscanf(input,"%d", &i);
fscanf(input," %s", name);
fscanf(input," %s", stat);
fscanf(input," %d", &j);
printf("pid : %d name: %s status: %s ppid: %d", i, name, stat, j);

If you are facing some kinds of buffer problem you can try following code...

int i, j;
char name[100], stat[100], temp[200];

fscanf(input, " %[^\n]s", temp);
sscanf(temp, "%d %s %s %d", &i, name, stat, &j);
printf("pid : %d name: %s status: %s ppid: %d\n", i, name, stat, j);
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号