-1

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 :)

Sz3jdii
  • 507
  • 8
  • 23
  • 1
    Offtopic: Please use slashes instead of backslashes in `#include` directives. – andreee May 22 '18 at 08:08
  • @andreee done :) – Sz3jdii May 22 '18 at 08:09
  • 1
    There are also some other problems with your code... please fix them first (hint: main arguments, use of '->', ...) – andreee May 22 '18 at 08:10
  • 3
    The arguments for `main` do not work like that, should be `int main(int argc, char *argv[])`. You also don't need to supply `program.exe` as an argument (previous edit): it is done for you as `argv[0]`. – Weather Vane May 22 '18 at 08:11

1 Answers1

1

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).

andreee
  • 4,459
  • 22
  • 42
  • Thank you! Can you please add small description or just summarize how your program works? :) EDIT: Sorry i didn't see that you've already done it :D – Sz3jdii May 22 '18 at 08:33
  • 1
    Done! Please accept this as an answer if it worked for you. Thanks. – andreee May 22 '18 at 08:39
  • 2
    *Do not return the size from main as this is reserved for returning error codes.* Not only that - the return value of a function is likely limited in range to something like `0`-`255`. – Andrew Henle May 22 '18 at 09:37
  • @andreee Can you please describe what is this part doing? `memset(buf, 0, BUF);` – Sz3jdii May 22 '18 at 11:01