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

Invalid use of incomplete type 'DIR'

本文关键字:DIR 类型 用不完 无效      更新时间:2023-10-16

我正在尝试编译这段代码,它在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://program files"这样的用户输入并获得"正确的"路径"c: program files *"(除了星号-或"F://"->"F:*")。我还使用这个变量来获取具有绝对路径值的目录列表,因为ep->d_name(当然是在一些readdir()之后)返回一个相对于somepath的路径。

在Linux上,我得到一个编译器错误(对于"dp->dd_name"):

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

我忘了什么吗?还是逻辑错误?

编辑:我已经添加了包含(我已经使用)以上

/* 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存在于结构体dient中,该结构体给出了目录的名称

您没有声明DIR的类型!在Posix系统上,您应该说,

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

然而,在Windows上,你没有这些功能。相反,您可以使用Windows API文件系统函数。

是。您错过了包含头文件。

dirent.h

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.

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

这不是要忘记包括一些头或定义,现在我已经面临这个问题,但不是错误,它是警告。

My files.h;

class Files
{
public:
    explicit Files(const char *p_path = 0);
    ~Files();
    /* ....  */
private:
    std::string path;
}

My 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]

free(p_dir);更改delete p_dir;后,两个警告都消失了。我不知道确切的原因,但听起来像DIR *型的行为像void *。我只是随便猜一下。