我在C語言中總初學者,我試圖寫一個程序,讀取在/ proc /「STAT」文件的價值。它適用於前幾個條目,但它會返回「分段錯誤(核心轉儲)」。 到目前爲止,我發現了錯誤與內存分配的事,但我似乎無法找到一個方法來解決它。 到目前爲止我的代碼是:分割錯誤,而分配內存
char* readFile(char* filename)
{
FILE *fp;
struct stat buf;
fp=fopen(filename,"r");
stat(filename,&buf);
char *string = malloc(buf.st_size);
char *s;
while(!feof(fp))
{
s=malloc(1024);
fgets(s,1024,fp);
s[strlen(s)-1]='\0';
strcat(string,s);
}
return string;
}
char* readStat(char* path, int statNumber)
{
char* str = malloc(sizeof(readFile(path)));
str = readFile(path);
char * pch = malloc(sizeof(str));
char * vals;
pch = strtok (str," ");
int i = 1;
while (pch != NULL)
{
if(i == statNumber)
vals = pch;
pch = strtok(NULL, " ");
i++;
}
return vals;
}
謝謝,這個伎倆! – user1946334 2013-05-03 12:45:14