Trying to made my own ls command, using the stat structure to extract inode numbers of files, but continuous failure. here is my code:
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <string.h>
int main(int argc, char* argv[])
{
DIR *mydir;
struct dirent *myfile;
struct stat mystat;
mydir = opendir("./");
int print = 0;
while((myfile = readdir(mydir)) != NULL)
{
printf("%ld %s\n", mystat.st_ino , myfile->d_name);
}
closedir(mydir);
}
Here is the output i am getting:
140734253789760 ls.c
140734253789760 ..
140734253789760 .
140734253789760 pwd.o
140734253789760 ls.o
140734253789760 Untitled Document
140734253789760 test.c
140734253789760 usr
140734253789760 ls
140734253789760 pwd
140734253789760 install_flash_player_11_linux.x86_64.tar.gz
140734253789760 readme.txt
140734253789760 pwd.c
140734253789760 Assignment-01-Scripting.pdf
140734253789760 LGPL
140734253789760 test.o
140734253789760 s1.sh
140734253789760 libflashplayer.so
Now If I ls -ai in the terminal I gets this:
655636 . 1060694 LGPL 680478 ls.o 674765 readme.txt 680539 Untitled Document
674665 .. 680512 libflashplayer.so 680562 pwd 680524 s1.sh 1060712 usr
680479 Assignment-01-Scripting.pdf 680503 ls 684547 pwd.c 684552 test.c
674770 install_flash_player_11_linux.x86_64.tar.gz 684548 ls.c 680510 pwd.o 680589 test.o
Stat can't get the inode number because it was not initialized by any file, to initialize it with a file following code is used:
DIR *mydir;
struct dirent *myfile;
struct stat mystat;
if (stat(myfile->d_name, &mystat) == -1)
{
perror("stat");
exit(EXIT_FAILURE);
}
printf("%ld %s\n",(long) mystat.st_ino , myfile->d_name);