I'm trying to write a simple implementation of the ls
command, close to ls -l
, but not exactly the same.
Here's what I have so far
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
#include <unistd.h>
#include <iostream>
#include <stdio.h>
#include <time.h>
using namespace std;
int main(int argc, char **argv)
{
if(argc != 2)
{
cout << "Usage: ./Asg4 <directoryName>" << endl;
return -1;
}
struct stat sb;
DIR *d;
struct dirent *dir;
d = opendir(argv[1]);
if(d)
{
while((dir = readdir(d)) != NULL)
{
stat(dir->d_name, &sb);
printf("%ld\t %s\t%lo\t%ld\t%lld\t%s\n", sb.st_ino, sb.st_dev, (unsigned long) sb.st_mode, (long) sb.st_nlink, (long long) sb.st_size, ctime(&sb.st_mtime));
}
closedir(d);
}
return 0;
}
But when I execute it on any given directory, it gives me a segmentation fault. Any ideas?
In response to Loki Astari's answer, I changed the printf to
printf("%ld\t %d\t%lo\t%ld\t%lld\t%s\n", (long) sb.st_ino, (int) sb.st_dev, (unsigned long) sb.st_mode, (long) sb.st_nlink, (long long) sb.st_size, ctime(&sb.st_mtime));
which seems to have resolved the segmentation fault.