How to use dirent.h correctly

陌路散爱 提交于 2019-12-24 08:27:38

问题


I am new to C++ and I am experimenting with the dirent.h header to manipulate directory entries. 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. 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;
}

回答1:


If you are using C++, don't use char * or arrays, use 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() );



回答2:


Change:

char *dirname = 0;

to:

char dirname[PATH_MAX] = "";


来源:https://stackoverflow.com/questions/3029633/how-to-use-dirent-h-correctly

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!