c - 提取 proc/status linux 文件的一部分

标签 c arrays linux string fedora

首先,我完全是 linux 和 C 语言的初学者,当涉及到字符串时,我无法将 C 与 c++ 或 java 联系起来!我正在使用 Fedora16 - linux - 我想读取一个 proc/[pid]/status 文件以从中获取特定信息,例如 PPID 和状态,然后我应该在屏幕上打印这些信息 - 命令行终端 -。这必须通过在 gedit 中编写 c 脚本来完成。我唯一的问题是我是 c 的新手,在 c 中处理字符串对我来说似乎非常令人沮丧!我已经打开文件并通过执行 c 文件在我的终端上查看它。有没有任何可能的方法将整个内容存储在一个字符串变量中,然后我可以将它标记化并将数据 block 存储在字符串数组而不是 char 数组中,然后我知道我想要的数据在数组中的位置并且我可以访问它?

这是我的代码

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>

void main()
{


const char line[200];
const char junk[200];

FILE *file = fopen("/proc/14/status", "r");

// while not end of the file
while(!feof(file)) {

fscanf(file,"%s",line); //Get text into line array

printf("%s\n", line);

//fscanf(file,"%[ \n\t\r]s",junk); //Remove any 'white space' characters

               }//end while

fclose(file);

}

终端输出:

enter image description here

最佳答案

一开始有两点不对

  1. line 不应该是 const
  2. while (!feof(file)) 几乎总是错误的。

修复涉及做类似的事情

while (fscanf(file, "%199s", line) == 1)

这将循环直到没有更多数据并防止 line 溢出。

这将解决一些问题,另一件事相当复杂,首先尝试使用 fgets() 而不是 fscanf(),它将消耗文件中的行,包括'\n' 和嵌入的空格

while (fgets(line, sizeof(line), file) != NULL)

然后您可以尝试 sscanf() 检查它的返回值以确保它成功。

/proc/self/status 的内容可以看出,strchr() 可以很好地分割感兴趣的部分。

这是一个例子:

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

int
main(void)
{
    FILE *file;
    char line[100];
    file = fopen("/proc/self/status", "r");
    if (file == NULL)
        return -1; /* Failure to open /proc/self/stat -- very unlikely */
    while (fgets(line, sizeof(line), file) != NULL)
    {
        char *tail;
        char *key;
        char *value;
        tail = strchr(line, '\n');
        if (tail != NULL)
            *tail = '\0'; /* remove the trailing '\n' */
        tail = strchr(line, ':');
        if (tail != NULL)
        {
            tail[0] = '\0';
            key = strdup(line);
            if (key == NULL)
                continue;
            tail += 1;
            while ((tail[0] != '\0') && (isspace((int) tail[0]) != 0))
                tail++;
            value = strdup(tail);
            if (value != NULL)
            {
                fprintf(stderr, "%s --> %s\n", key, value);
                /* You could do something now with key/value */
                free(value);
            }
            free(key);
        }
    }
}

关于c - 提取 proc/status linux 文件的一部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33184576/

相关文章:

c - 在 C99 模式之外使用的“for”循环初始声明

java - Java中的数组 "remember"它们的类型如何?

linux - 如何将共享库打包成deb包

c - 将 3 个整数写入文件并使用 fprintf 和 fscanf 恢复它们

c - 使用 GNU 工具链在 Windows 命令行上运行 ARM/C

c - C语言中bitset类型使用什么类型

java - 我可以将数组作为参数传递给 Java 中具有可变参数的方法吗?

c - 在 C 中返回指向字符串的指针时出现问题

linux - 通过局域网查看 xampp wordpress 站点

linux - 无法启动瘦服务器