-1
我正在尝试读取proc/stat文件,但我无法确定,但我确信我的代码正在工作,因为我尝试读取另一个文件,并且它工作得很完美...... 这里是代码:无法在linux中读取文件
#include <stdio.h>
#include <stdlib.h> // for the malloc
int main (int argc,char *argv[])
{
char *file_name = "/proc/stat";
char *contents;
FILE *file;
int filesize = 0;
file = fopen(file_name, "r");
if(file != NULL)
{
//get the file size
fseek(file, 0, SEEK_END);
filesize = ftell(file);
fseek(file, 0, SEEK_SET);
printf("the file size is: %d\n", filesize);
contents = (char *)malloc(filesize+1); // allocate memory
fread(contents, filesize,1,file);
contents[filesize]=0;
fclose(file);
printf("File has been read: %s \n", contents);
}
else
{
printf("the file name %s doesn't exits", file_name);
}
return 0;
}
更换'的printf( “文件名%s不退出”,FILE_NAME);'和'PERROR( ' – 2013-02-24 13:21:41
如果你不检查你使用的所有I/O函数的返回值,并根据它们做出反应,你将永远无法找出代码失败的原因。帮你一个忙,**总是**检查所有的人。 – Mat 2013-02-24 13:22:06
请勿投射malloc。如果在此代码中移除malloc的转换时出现错误,那是因为您使用的是C++编译器。如果你想使用C++,使用C++'new'。否则,使用C编译器。将自己限制在两种语言的共同子集是不可行的;在过去的10年中,C++在当今的通用C库中没有采用C的特性。你不能用C++编译器构建它们。你会浪费几个小时的时间将代码转换为稍不清晰的,与C++兼容的代码来编译C++吗?只需使用C编译器。 – Sebivor 2013-02-24 13:34:00