如何正确使用dirent.h [英] How to use dirent.h correctly
本文介绍了如何正确使用dirent.h的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是C ++的新手,我正在试验dirent.h头来操作目录条目。下面的小应用程序编译,但pukes后,你支持目录名称。有人可以给我一个提示吗? int退出是提供一个while循环。我删除了该循环,试图隔离我的问题。
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.
谢谢!
#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;
}
推荐答案
如果使用C ++,不要使用char *或数组,使用std :: string:
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() );
这篇关于如何正确使用dirent.h的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文