c - 打开不带扩展名的文件

标签 c linux unix ubuntu

我需要使用 fopen() 系统调用在/proc/文件夹中打开一个没有扩展名的文件,不幸的是它不起作用。

这是代码

#include <stdio.h>
#include <strings.h>
#include <errno.h>

int main(void){
    FILE *f;
    int size;

    //open /proc/meminfo
    f = fopen("/proc/meminfo", "r");
    printf("errno after open: %s\n", strerror(errno)); //errno = Success

    //create buffer
    fseek(f,0,SEEK_END);
    size = ftell(f);
    printf("size: %d\n", size);
    char buffer[size];
    bzero(buffer,size);
    fseek(f,0,SEEK_SET);

    //fill the buffer and print
    fread(buffer,sizeof(char),size,f);
    printf("%s\n", buffer);

    return 0;
}

问题是size = 0,errno是“Success”,所以,即使打开了文件也没有读取。

你有什么想法吗?

提前致谢!

最佳答案

/proc 中的某些(大多数?)文件大小为 0,因为它们的内容是在读取时动态生成的。因此,将 EOF 作为普通文件读取以获取内容。这有效:

#include <stdio.h>

int main(void){
    FILE *f;
    int c;

    f = fopen("/proc/meminfo", "r");

    if (!f) {
        return -1;
    }

    while ( (c = fgetc(f)) != EOF) {
        printf("%c",c);
    }

    return 0;
}

关于c - 打开不带扩展名的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28900820/

相关文章:

c++ - 将字符串拆分为 3d 数组

C - 交换单链表中的第一个和最后一个元素

c - 使用具有返回类型的递归函数在 C 中进行二分搜索

linux - Centos 6.9 - MISCONF Redis 配置为保存 RDB 快照,但目前无法在磁盘上持久化

unix - 如何在vi中编辑的文件中添加行号?

linux - 使用 UNIX BASH 将文件复制到其他虚拟机

c++ - 如何编写C .so 库来替代现有的C++ .so 库?

python - Ansible - When 语句使用变量

命令行中的 Java NoClassDefFoundError

linux - 使用文件内容创建新目录