Search code examples
clinuxstat

Program wchich reads its own size from st_size


Using stat() function and main function arguments I have to write a program which reads and prints its own size from st_size. What I've already tried:

#include <sys/types.h> 
#include <sys/stat.h> 
int main( const char * szFileName ) 
{ 
  struct stat fileStat; 
  int err = stat( szFileName, &fileStat ); 
  if (0 != err) return 0; 
  return fileStat.st_size; 
}

But I don't realy understand how to edit it to read it's own size.

Thank you for your time and all the help :)


Solution

  • Since there are some minor mistakes with your program, I have made a small effort to write a simple, working version:

    #include <sys/types.h>
    #include <sys/stat.h>
    #include <stdlib.h>
    #include <unistd.h>
    #include <string.h>
    #include <stdio.h>
    
    #define BUF 20
    
    int main(int argc, char **argv)
    {
      struct stat fileStat;
      char buf[BUF];
      int err;
    
      err = stat( argv[1], &fileStat ); // No argv sanity checks
      if (0 != err)
        return EXIT_FAILURE;
    
      memset(buf, 0, BUF);
      snprintf(buf, BUF, "%d\n", fileStat.st_size);
      write(0, buf, BUF);
    }
    

    Some further comments:

    • main(int argc, char** argv) is the way to go for taking parameters. argv[1]contains the first argument, if provided argv[0] is the program name. See here.
    • Do not return the size from main as this is reserved for returning error codes. Also, return 0 means success in UNIX/Linux. By using write, you can also pipe the result for further processing.

    To read the program's own size (as the OP requested), just compile (gcc -o prog stat.c) and run (./prog prog).