我需要使用 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/