-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