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

标签 c++ c

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

相关文章:

c++ - gazebo ros插件报错: Undefined symbols for architecture x86_64

c++ - g++ 为定义的函数抛出大量 'undefined reference'

c - 相同的字符串。一个人行为不端

c - 当 for 循环中有逗号而不是分号时,没有编译器警告

c++ - 为什么程序员要同时使用 std::bad_alloc 和 std::exception。仅 std::exception 是不够的

mac/eclipse 上的 c++ 在崩溃时不显示错误

c++ - 事务中的sqlite3_step(stmt)失败,错误5,而没有调用我的忙处理程序

c - 如何使用 linux 内核中的 lockdep 功能进行死锁检测

C++ Windows MFC 并发 : Get thread to wait until particular state achieved

c - 安装AVR开发平台for mac时架构x86_64错误