简体   繁体   English

解析文件时fscanf格式化字符串

[英]fscanf format string while parsing file

I am new in Linux. 我是Linux新手。 I am developing a C application. 我正在开发一个C应用程序。 I need uid of several processes. 我需要几个过程的uid。 What I am trying to do is parsing /proc/pid/status file to get Uid of processes. 我想要做的是解析/proc/pid/status文件来获取进程的Uid

Name:    init
State:    S (sleeping)
Tgid:    1
Pid:    1
PPid:    0
TracerPid:    0
Uid: 0    0     0     0   0

To parse this file I am thinking of using fscanf function. 要解析这个文件,我正在考虑使用fscanf函数。

Here I want to write some generic code, which works for different lengths of process. 在这里,我想编写一些通用代码,它适用于不同长度的进程。 But I am confused what is really a good way to parse this file. 但我很困惑什么是解析这个文件的好方法。 Can any one help me? 谁能帮我?

Edit: Here is what I have got. 编辑:这是我得到的。 But I have created unnecessary array. 但我创建了不必要的数组。 I just want to skip till Uid. 我只想跳到Uid。 But I don't know how to. 但我不知道该怎么做。

  char temp[8][1024];

  struct FILE * pFile;

  pFile = fopen ("/proc/1/status","w+");


fscanf(pFile,"%[^\n] %[^\n] %[^\n] %[^\n] %[^\n] %[^\n] %s %s",temp[0],temp[1],temp[2],temp[3],temp[4],temp[5],temp[6],temp[7]);

printf(" User id %s \n",temp[7]);

Thanks 谢谢

You can read the file line by line with getline (it's part of c++, and a GNU extensions in C, not standard C) until you find the Uid, then stop: 您可以逐行读取文件getline (它是c ++的一部分,C中的GNU扩展,而不是标准C),直到找到Uid,然后停止:

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

int 
main(void)
{   
    FILE * fp; 
    char * line = NULL;
    size_t len = 0;
    ssize_t read;

    fp = fopen("/proc/20204/status", "r");
    if (fp == NULL)
        exit(EXIT_FAILURE);

    while ((read = getline(&line, &len, fp)) != -1) {
            char *content;
            content = strtok(line, ":");

            printf("content: %s\n", content);
            if(strncmp(content, "Uid", 3) == 0)
            {   
                    printf("get it:\n");
                    //get the User ID
                    printf("%s\n", strtok(NULL, ":"));
                    break;
            }   
       }  

    if (line)
        free(line);
    exit(EXIT_SUCCESS);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM