使用 ifstream::open "meminfo",fileLen 为 -1

发布于 2024-12-21 15:38:55 字数 733 浏览 3 评论 0 原文

下面是代码:

#include <iostream>
#include <stdio.h>
#include <unistd.h>
#include <fstream>
#include <memory.h>


int main()
{
std::ifstream file;
file.open("/proc/meminfo");
if(file.fail())
    return 0;

file.seekg(0, std::ios::end);
int fileLen = file.tellg();
file.seekg(0, std::ios::beg);

char buffer[fileLen + 1];
memset(buffer, 0, fileLen + 1);
file.read(buffer, fileLen + 1);
if(file.fail())
    return 0;

unsigned long long total = 0;
unsigned long long free = 0;
sscanf(buffer, "%*s %llu%*s%llu", &total, &free);
file.close();
return 1;
}

在代码中,fileLen是-1,但我不知道原因。如果 ifstream 打开不同的文件,例如 1.txt,则程序是正确的。 最后,感谢您的帮助

Below is the code:

#include <iostream>
#include <stdio.h>
#include <unistd.h>
#include <fstream>
#include <memory.h>


int main()
{
std::ifstream file;
file.open("/proc/meminfo");
if(file.fail())
    return 0;

file.seekg(0, std::ios::end);
int fileLen = file.tellg();
file.seekg(0, std::ios::beg);

char buffer[fileLen + 1];
memset(buffer, 0, fileLen + 1);
file.read(buffer, fileLen + 1);
if(file.fail())
    return 0;

unsigned long long total = 0;
unsigned long long free = 0;
sscanf(buffer, "%*s %llu%*s%llu", &total, &free);
file.close();
return 1;
}

In the code ,fileLen is -1, but I don't know the reason. If ifstream opens a different file, like 1.txt, the program is correct.
at last,thanks for your help

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

白馒头 2024-12-28 15:38:56

我认为原因可能是 /proc/meminfo 实际上并不是一个文件。 /proc 不包含真正的文件,它们只是系统当前状态的快照。

http://tldp.org/LDP/Linux-Filesystem-Hierarchy/html /proc.html

I think the reason could be /proc/meminfo is not actually a file. /proc does not contain real files, they are just snapshot of the current state of the system.

http://tldp.org/LDP/Linux-Filesystem-Hierarchy/html/proc.html

梦里梦着梦中梦 2024-12-28 15:38:55

/proc 的内容不是真实的文件,因此没有实际大小。不要尝试获取它们的大小,而是简单地正常读取和解析它们。

The contents of /proc are not real files, and hence don't have actual sizes. Do not attempt to get their sizes, but instead simply read and parse them normally.

旧城烟雨 2024-12-28 15:38:55

因为这不是一个普通的文件:

proc 文件系统是一个以 /proc 为根的伪文件系统,其中包含与内核运行时状态相关的用户可访问对象,以及在其上运行的执行进程。使用“伪”是因为 proc 文件系统仅作为其显示的内存中内核数据结构的反映而存在。这就是为什么 /proc 中的大多数文件和目录的大小都是 0 字节。

Because this is not a ordinary file:

The proc filesystem is a pseudo-filesystem rooted at /proc that contains user-accessible objects that pertain to the runtime state of the kernel and, by extension, the executing processes that run on top of it. "Pseudo" is used because the proc filesystem exists only as a reflection of the in-memory kernel data structures it displays. This is why most files and directories within /proc are 0 bytes in size.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文