使用 ifstream::open "meminfo",fileLen 为 -1
下面是代码:
#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
,则程序是正确的。
最后,感谢您的帮助
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我认为原因可能是
/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
/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.因为这不是一个普通的文件:
Because this is not a ordinary file: