简体   繁体   English

如何正确使用dirent.h

[英]How to use dirent.h correctly

I am new to C++ and I am experimenting with the dirent.h header to manipulate directory entries. 我是C ++的新手,我正在尝试使用dirent.h标头来处理目录条目。 The following little app compiles but pukes after you supple a directory name. 以下小应用程序可以编译,但是在您添加目录名称后会呕吐。 Can someone give me a hint? 有人可以给我提示吗? The int quit is there to provide a while loop. int quit提供了while循环。 I removed the loop in an attempt to isolate my problem. 为了解决我的问题,我删除了循环。

thanks! 谢谢!

#include <iostream>
#include <dirent.h>

using namespace std;

int main()
{

char *dirname = 0;
    DIR *pd = 0;
    struct dirent *pdirent = 0;

    int quit = 1;



    cout<< "Enter a directory path to open (leave blank to quit):\n";
    cin >> dirname;

    if(dirname == NULL)
    {
        quit = 0;

    }
        pd = opendir(dirname);

    if(pd == NULL)
    {
        cout << "ERROR: Please provide a valid directory path.\n";
    }


    return 0;
}

If you are using C++, don't use char * or arrays, use std::string: 如果您使用的是C ++,请不要使用char *或数组,请使用std :: string:

#include <string>
....   
string dirname;
cout<< "Enter a directory path to open (leave blank to quit):\n";
getline( cin, dirname );
if ( dirname == "" ) {
   exit(1);
}
....   
pd = opendir(dirname.c_str() );

Change: 更改:

char *dirname = 0;

to: 至:

char dirname[PATH_MAX] = "";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM