c - 解析文件时的 fscanf 格式字符串

标签 c linux gcc scanf

我是 Linux 新手。我正在开发 C 应用程序。我需要几个进程的uid。我想做的是解析 /proc/pid/status 文件以获取进程的 Uid

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

为了解析这个文件,我正在考虑使用 fscanf 函数。

在这里,我想编写一些通用代码,适用于不同长度的流程。但是我很困惑什么是解析这个文件的真正好方法。谁能帮帮我?

编辑: 这是我得到的。但是我创建了不必要的数组。我只想跳到 Uid。但我不知道该怎么做。

  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]);

谢谢

最佳答案

你可以用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);
}

关于c - 解析文件时的 fscanf 格式字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21818928/

相关文章:

c - OpenGL 纹理,黑色方 block

linux - 虚拟 IP 配置不起作用,我仍然收到地址已在使用错误

linux - Linux 上的 Swift 有哪些限制?

python - Cython 编译将文本附加到文件名,如何摆脱它?

arrays - 在使用字符串数组时使用 scanf_s 的正确方法是什么?

c - 如何将头文件和 C 文件一起编译?

c - 链接 C 代码失败

c - 将套接字绑定(bind)到网络接口(interface)

c++ - 在模板实例化期间重载查找

linux - 为什么 gcc 在调用 “halt” 之后在程序中放置 “main” 指令?