使用不完整类型'DIR'无效

问题描述 投票:1回答:6

我正在尝试编译此代码,它在Windows上运行良好,在Linux(Code :: Blocks)上:

/* Edit: Includes */
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
#include <...>
/**/

/* === */

/* Function code */
DIR *dp;
dirent *ep;
string name_parent;

dp = opendir(somepath);
name_parent = dp->dd_name; //error
/**/

由于Windows上的路径名不区分大小写,因此我可以读取“c://程序文件”之类的用户输入并获取“正确”路径“C:\ Program Files *”(星号除外 - 或“F: //“ - >”F:*“)。我还使用此变量来获取具有绝对路径值的目录列表,因为ep-> d_name(当然在一些readdir()之后)返回相对于某路径的路径。

在Linux上,我收到编译器错误(对于“dp-> dd_name”):

错误:无效使用不完整类型'DIR'

我忘记了什么吗?或者是否存在逻辑错误?

编辑:我已添加上面的包含(我已经在使用)。

c++ directory dir directory-listing
6个回答
3
投票
/* Edit: Includes */
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
#include <...>
/**/

/* === */

/* Function code */
DIR *dp;
dirent *ep;
string name_parent;

dp = opendir(somepath);
ep = readdir(dp);
name_parent = ep->d_name;

/**/

变量d_name存在于struct dirent中,它提供了目录的名称


2
投票

你没有声明DIR的类型!在Posix系统上,你会说,

#include <sys/types.h>
#include <dirent.h>

但是,在Windows上,您没有这些功能。相反,你可以使用Windows API filesystem functions


1
投票

是。你错过了包括头文件。

dirent.h

1
投票

DIR的内部结构未指定,因此您不应该依赖它并期望您的代码可移植。

Windows的glib源代码说DIR

/*
 * This is an internal data structure. Good programmers will not use it
 * except as an argument to one of the functions below.

0
投票

显然,类型DIR没有在您尝试使用它时定义。也许你忘记了#include


0
投票

它现在不会忘记包括一些标题或定义我遇到了这个问题,但没有错误它是警告。

我的files.h;

class Files
{
public:
    explicit Files(const char *p_path = 0);
    ~Files();

    /* ....  */
private:
    std::string path;
}

我的files.cpp;

#include <iostream>

#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <sys/types.h> // I added this line with @Kerrek SB's advice but nothing changed
#include <dirent.h>
#include <files.h>

static DIR *p_dir = NULL;
static struct dirent *p_ent = NULL;
Files::Files(const char *p_path)
{
    if (p_path == NULL)
    {
        std::cerr << "PATH is NULL" << std::endl;
        exit(EXIT_FAILURE);
    }
    path = p_path;
    p_dir = opendir(p_path);
    if (p_dir == NULL)
    {
        std::cerr << "Cannot open " << path << std::endl;
        exit(EXIT_FAILURE);
    }
}

Files::~Files()
{
    if (p_dir)
    {
        /* Here is my warning occuring in this line and the definition
           line p_dir 'static DIR *p_dir = NULL' */
        delete p_dir; // After changing this line with 'free(p_dir);' warnings gone.
        p_dir = NULL;
    }
}

定义行(static DIR *p_dir = NULL;)的警告是'p_dir' has incomplete type,删除行(delete p_dir;)的警告是possible problem detected in invocation of delete operator: [-Wdelete-incomplete]

delete p_dir;改变free(p_dir);后,两个警告都消失了。我不知道它的确切原因,但它听起来像DIR *类型的行为像void *。我只是疯狂猜测。

希望这可以帮助。

© www.soinside.com 2019 - 2024. All rights reserved.