我试图写一个ls
命令的简单实现,接近ls -l
,但不完全相同。
这是我到目前为止所拥有的
#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;
}
但是当我在任何给定目录上执行它时,它会给我一个分段错误。有什么想法吗?
为了回应Loki Astari的回答,我将printf更改为
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));
似乎解决了分段错误。
答案 0 :(得分:2)
当我编译时,我得到一些令人讨厌的警告:
xc.cpp:28:54: warning: format specifies type 'long' but the argument has type '__darwin_ino64_t' (aka 'unsigned long long') [-Wformat]
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));
~~~ ^~~~~~~~~
%llu
xc.cpp:28:65: warning: format specifies type 'char *' but the argument has type 'dev_t' (aka 'int') [-Wformat]
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));
~~ ^~~~~~~~~
%d
那些看起来像会崩溃的错误 它也是使用C ++而不是C的好广告.C ++流没有这个问题。