-1

私はproc/statファイルを読み取ろうとしていましたが、別のファイルを読み取ろうとしたため、コードが機能していると確信していましたが、完全に機能しました..コードは次のとおりです。

#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;

}

4

1 に答える 1

2

/proc 内の特殊ファイルのサイズを特定できず、最後までシークできません。それらのコンテンツはオンザフライで生成されます。これらのファイルでは、EOF に遭遇するまで読み続ける必要があります。取得するデータ量を事前に知ることはできません。

したがって、短い読み取りが得られるまで、たとえば 512 バイト ブロックでデータを読み取り続けます。その後、これ以上データを読み取ることができないことがわかります。

編集:過去の質問ですでにこれに回答したことが思い浮かびました:/proc/[pid]/cmdline file size

于 2013-02-24T13:26:04.337 に答える