Hi, I am a newbie in Linux. I hope someone can guide me through. I wanted to do a C program such that it can display the following output:
1) the type of file
2) access permissions
3) size of the file
4) inode number
5) modify, access and change timestamp.
I got some code from the internet and combine a little of my edited code.
Code:
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/stat.h>
#include <sys/types.h>
int main( int argc, char *argv[] )
{
int i; struct stat buf; char *p;
for (i = 1; i < argc; i++)
{
printf("%s: ", argv[i]);
if ( lstat(argv[i], &buf) < 0 )
{
perror("lstat error"); continue;
}
if( S_ISREG( buf.st_mode ) ) p = "regular file";
else if ( S_ISDIR( buf.st_mode ) ) p = "directory";
else if ( S_ISCHR( buf.st_mode ) ) p = "character special";
else if ( S_ISBLK( buf.st_mode ) ) p = "block special";
else if ( S_ISFIFO( buf.st_mode ) ) p = "fifo";
else if ( S_ISLNK( buf.st_mode ) ) p = "symbolic link";
else if ( S_ISSOCK( buf.st_mode ) ) p = "socket";
else p = "**unknown file type";
}
int main(int argc, char **argv)
{
if(argc != 2)
return 1;
struct stat fileStat;
if(stat(argv[1],&fileStat) < 0)
return 1;
printf("Output Data %s\n",argv[1]);
printf("---------------------------\n");
printf("Size of the File: \t\t%d bytes\n",fileStat.st_size);
printf("No. of Links: \t%d\n",fileStat.st_nlink);
printf("File inode: \t\t%d\n",fileStat.st_ino);
printf("%s\n", p); /* print file type */
printf("File Permissions: \t");
printf( (S_ISDIR(fileStat.st_mode)) ? "d" : "-");
printf( (fileStat.st_mode & S_IRUSR) ? "r" : "-");
printf( (fileStat.st_mode & S_IWUSR) ? "w" : "-");
printf( (fileStat.st_mode & S_IXUSR) ? "x" : "-");
printf( (fileStat.st_mode & S_IRGRP) ? "r" : "-");
printf( (fileStat.st_mode & S_IWGRP) ? "w" : "-");
printf( (fileStat.st_mode & S_IXGRP) ? "x" : "-");
printf( (fileStat.st_mode & S_IROTH) ? "r" : "-");
printf( (fileStat.st_model & S_IWOTH) ? "w" : "-");
printf( (fileStat.st_mode & S_IXOTH) ? "x" : "-");
printf("\n\n");
return 0;
}
exit(0);
}
I have done the first four points however, when I tried to compile and run, there are some errors.
Quote:
test.c: In function ‘main’:
test.c:40:5: warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘__off_t’ [-Wformat=]
printf("File Size: \t\t%d bytes\n",fileStat.st_size);
^
test.c:41:5: warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘__nlink_t’ [-Wformat=]
printf("Number of Links: \t%d\n",fileStat.st_nlink);
^
test.c:42:5: warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘__ino_t’ [-Wformat=]
printf("File inode: \t\t%d\n",fileStat.st_ino);
^
test.c:54:22: error: ‘struct stat’ has no member named ‘st_model’
printf( (fileStat.st_model & S_IWOTH) ? "w" : "-");
|
And as for the last point, I am aware that I need to use "stat" to run but I am unsure how to do so. Please assist me. Thanks