1

我正在尝试编译这段代码,它在 Windows 上运行良好,在 Linux 上(代码::块):

/* 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”的无效使用

我是不是忘记了什么?还是有逻辑错误?

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

4

6 回答 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 中,它给出了目录的名称

于 2014-04-15T05:39:57.253 回答
2

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

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

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

于 2011-07-31T11:55:37.157 回答
1

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

dirent.h
于 2011-07-31T11:54:01.460 回答
1

a 的内部结构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.
于 2011-08-01T14:02:02.437 回答
0

显然,在DIR您尝试使用该类型时并未定义该类型。也许你忘了一个#include

于 2011-07-31T11:53:56.310 回答
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;with后free(p_dir);,两个警告都消失了。我不知道它的确切原因,但它听起来像DIR *type 的行为void *。我只是在胡乱猜测。

希望这可以帮助。

于 2018-12-03T21:17:07.823 回答