gpt4 book ai didi

c++ - 分段故障打印文件特征

转载 作者:太空宇宙 更新时间:2023-11-04 08:13:55 25 4
gpt4 key购买 nike

我正在尝试编写 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));

这似乎解决了段错误。

最佳答案

当我编译时,我收到一些讨厌的警告:

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++ 流没有这个问题。

关于c++ - 分段故障打印文件特征,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37061885/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com