使用readdir()获取文件名后得到stat()错误

时间:2014-12-24 18:48:38

标签: unix stat

我有这个函数,它将一些目录中的文件信息放入字符串中。 问题出在这里:

if (stat(dirread->d_name, &sb) == -1)

所以有文件要读,我测试一下,但由于某种原因,stat函数总是返回-1。

char* content(char folder_name[], char continut[])
{
    DIR *diropen;
    struct dirent *dirread;

    if ((diropen = opendir(folder_name)) == NULL)
    {
        sprintf (continut,"Error opening directory\n",folder_name);
        return continut;
    }

    while ((dirread = readdir (diropen)) != NULL)
    {
        struct stat sb;
        memset(&sb, 0, sizeof sb);
        if (stat(dirread->d_name, &sb) == -1) {
            perror("stat");
            exit(EXIT_FAILURE);
        }

        strcat(continut,"File type:                ");

        switch (sb.st_mode & S_IFMT) {
        case S_IFBLK:  strcat(continut,"block device\n");            break;
        case S_IFCHR:  strcat(continut,"character device\n");        break;
        case S_IFDIR:  strcat(continut,"directory\n");               break;
        case S_IFIFO:  strcat(continut,"FIFO/pipe\n");               break;
        case S_IFLNK:  strcat(continut,"symlink\n");                 break;
        case S_IFREG:  strcat(continut,"regular file\n");            break;
        case S_IFSOCK: strcat(continut,"socket\n");                  break;
        default:       strcat(continut,"unknown?\n");                break;
        }

        sprintf(continut,"I-node number:            %ld\n", (long) sb.st_ino);
        ........
    }

    return continut;
}

出了什么问题?

0 个答案:

没有答案