gpt4 book ai didi

c++ - 使用 fscanf 读取/proc C++

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:14:42 24 4
gpt4 key购买 nike

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

例如,如果您正在读取 proc/meminfo,则 MemTotal %lu 会获取可用的 RAM 总量。那么 fscanf 会是这样的:

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

如何在使用 fscanf 获取某些值时遍历文件。

最佳答案

我写了一些代码来完成 [好吧,它不完全是 "/proc/meminfo",而是从 "/proc/something" 中读取数据前几天在工作中使用 scanf]。

原理是检查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;
}
}
}

这只是如何执行此操作的草图,但它应该会给您一个想法。

关于c++ - 使用 fscanf 读取/proc C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35373353/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com