使用 fscanf 从 /proc C++读取



我目前正在开始编写一个程序,该程序将使用fscanf/proc读取信息,但不确定从哪里开始。浏览手册页查找proc(5),我注意到您可以使用fscanf/proc目录中获取某些属性。

例如,如果您正在读取 RAM,MemTotal %lu proc/meminfo 获得 RAM 的总可用量。那么fscanf将如下所示:

unsigned long memTotal=0;
FILE* file = fopen("/proc/meminfo", "r");
fscanf(file, "MemTotal %lu", &memTotal);

在使用fscanf获取某些值时,我将如何迭代文件。

我写了一些代码来做[嗯,它不完全是"/proc/meminfo",但使用scanf"/proc/something"读取数据]前几天在工作中这样做。

原理是检查fscanf的返回值。它将是EOF,0或1表示输入结束,没有得到任何东西并找到了您要查找的内容。如果结果是 EOF,则退出循环。如果所有采样点均为 0,则需要执行其他操作来跳过该行 - 我使用fgetc()周围的循环来读取该行。

如果你想阅读几个元素,最好使用某种列表来做到这一点。

我可能会做这样的事情:

std::vector<std::pair<std::string, unsigned long* value>> list = 
    { { "MemTotal %lu", &memTotal },
      { "MemFree %lu",  &memFree },
      ...
    };
bool done = false
while(!done)
{ 
     int res = 0;
     bool found_something = false;
     for(auto i : list)
     {
        res = fscanf(file, i.first.c_str(), i.second);
        if (res == EOF)
        {
           done = true;
           break;
        }
        if (res != 0)
        {
           found_something = true;
        }
     }
     if (!found_something)
     {
         // Skip line that didn't contain what we were looking for.
         int ch;
         while((ch = fgetc(file)) != EOF)
         {
             if (ch == 'n')
                break;
         }
     }
}

这只是如何做到这一点的草图,但它应该给你一个想法。

最新更新