-1

I was trying to read the proc/stat file but I couldn't though I am sure that my code is working because I tried reading another files and it worked perfectly .. here is the code:

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

}

I.el-sayed
  • 325
  • 1
  • 5
  • 18
  • Replace `printf("the file name %s doesn't exits", file_name);` with `perror( file_name );` – William Pursell Feb 24 '13 at 13:21
  • 3
    If you don't check the return values of all those I/O functions you're using, and react according to them, you'll never be able to figure out why your code fails. Do yourself a favor and **always** check all of them. – Mat Feb 24 '13 at 13:22
  • Don't cast malloc. If you're getting errors when you remove the cast of malloc in this code, it's because you're using a C++ compiler. If you want to use C++, use C++ `new`. Otherwise, use a C compiler. It's infeasible to restrict yourself to a common subset of the two languages; There are features of C that C++ hasn't adopted in the last 10 years used in common C libraries of today. You can't build these with a C++ compiler. Are you going to waste hours of your time converting that code to slightly less legible, C++ compatible code to compile in C++? Just use a C compiler. – autistic Feb 24 '13 at 13:34

1 Answers1

2

You cannot determine the size of special files in /proc and you can't seek to the end in them. Their contents are generated on-the-fly. With these files, you have to keep reading until you encounter an EOF. You cannot know how much data you're going to get beforehand.

So keep reading data in, say, 512 byte blocks, until you get a short read. Then you'll know that you can't read any more data.

Edit: It just occurred to me that I answered this in a past question already: /proc/[pid]/cmdline file size

Community
  • 1
  • 1
Nikos C.
  • 50,738
  • 9
  • 71
  • 96