C++ || Snippet – How To Display The Size Of A File Using Stat

The following is sample code which demonstrates the use of the “stat” function calls on Unix based systems.
The stat function returns information about a file. No permissions are required on the file itself, but-in the case of stat() and lstat() – execute (search) permission is required on all of the directories in path that lead to the file.
The “stat” system call returns a stat structure, which contains the following fields:
The following example demonstrates the use of the “st_size” struct parameter to display the size of a file.
12345678910111213141516171819202122232425262728293031323334353637383940
// ============================================================================// Author: K Perkins// Date: Oct 4, 2013// Taken From: http://programmingnotes.org/// File: Stat.cpp// Description: Demonstrate the use of the "stat" function to display the// size of a file// ============================================================================#include <iostream>#include <cstdlib>#include <unistd.h>#include <sys/types.h>#include <sys/stat.h>using namespace std; int main(int argc, char* argv[]){ // declare variables struct stat fileInfo; // the buffer to store file information // check to see if theres enough commandline args if(argc < 2) { cerr<<"n** ERROR - NOT ENOUGH ARGUMENTS!n" <<"nUSAGE: "<<argv[0]<<" <FILE NAME>n"; exit(1); } // get the file information if(stat(argv[1], &fileInfo) < 0) { cerr<<"nstat failed (file not found)n"; exit(1); } // display info to the screen cerr<<"nThe file ""<<argv[1]<<"" is "<<(int)fileInfo.st_size<<" bytesnn"; return 0;}// http://programmingnotes.org/
QUICK NOTES:
The highlighted lines are sections of interest to look out for.
The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.
The following is sample output:
./Stat Stat.cpp
The file "Stat.cpp" is 1170 bytes
Leave a Reply