使用C打开目录 [英] Open directory using C
问题描述
我接受通过命令行输入的路径。
当我这样做
DIR =执行opendir(参数[1]);
它不进入循环......即目录== NULL ...
我如何在命令行中输入传递到DIR指针???
无效的主要(INT C,焦炭**参数)
{
DIR * DIR;
结构的dirent *凹痕;
字符缓冲区[50];
的strcpy(缓冲液,ARGS [1]);
DIR =执行opendir(缓冲液); //这部分
如果(DIR!= NULL)
{
而((凹痕= READDIR(DIR))!= NULL)
的printf(dent-> d_name);
}
关闭(DIR);
}./a.out /根/试验用于运行程序..
./a.out - >以执行该程序
/根/测试 - >用户即有效路径输入
您真的应该发表您的code,但在这里不用。首先:
的#include<&stdio.h中GT;
#包括LT&;&dirent.h GT; INT主(INT C,字符* V []){
INT LEN;
结构的dirent * pDirent;
DIR * PDIR; 如果(C 2){
的printf(用法:testprog<&的dirname GT; \\ n);
返回1;
}
PDIR =执行opendir(ⅴ[1]);
如果(PDIR == NULL){
的printf(无法打开目录%s'\\ n,V [1]);
返回1;
} 而((pDirent = READDIR(PDIR))!= NULL){
的printf([%S] \\ n,pDirent-> d_name);
}
closedir(PDIR);
返回0;
}
您需要在您的情况下 ARGS [1]
不仅设置并指实际的目录进行检查。当这是运行于
testprog TMP
( TMP
是把我的当前目录下的子目录,但你可以使用任何有效的目录),我得到:
[]
[..]
[FILE1.TXT]
[file1_file1.txt]
[file2.avi]
[file2_file2.avi]
[file3.b.txt]
[file3_file3.b.txt]
请注意,您必须通过的目录的在,不是的文件的当我执行:
testprog TMP / FILE1.TXT
我得到:
无法打开目录'TMP / FILE1.TXT
,因为这是一个文件,而不是一个目录(如果你是偷偷摸摸的,你可以尝试使用 diropen(目录名(V [1]))
如果初始 diropen
失败)。
I am accepting the path through command line input.
When I do
dir=opendir(args[1]);
it doesnt enter the loop...i.e dir==null...
How do I pass the command line input to dir pointer???
void main(int c,char **args)
{
DIR *dir;
struct dirent *dent;
char buffer[50];
strcpy(buffer, args[1]);
dir = opendir(buffer); //this part
if(dir!=NULL)
{
while((dent=readdir(dir))!=NULL)
printf(dent->d_name);
}
close(dir);
}
./a.out /root/TEST is used to run the program..
./a.out --> to execute the program
/root/TEST --> input by the user i.e valid path
You should really post your code, but here goes. Start with:
#include <stdio.h>
#include <dirent.h>
int main (int c, char *v[]) {
int len;
struct dirent *pDirent;
DIR *pDir;
if (c < 2) {
printf ("Usage: testprog <dirname>\n");
return 1;
}
pDir = opendir (v[1]);
if (pDir == NULL) {
printf ("Cannot open directory '%s'\n", v[1]);
return 1;
}
while ((pDirent = readdir(pDir)) != NULL) {
printf ("[%s]\n", pDirent->d_name);
}
closedir (pDir);
return 0;
}
You need to check in your case that args[1]
is both set and refers to an actual directory. When this is run with:
testprog tmp
(tmp
is a subdirectory off my current directory but you can use any valid directory), I get:
[.]
[..]
[file1.txt]
[file1_file1.txt]
[file2.avi]
[file2_file2.avi]
[file3.b.txt]
[file3_file3.b.txt]
Note that you have to pass a directory in, not a file. When I execute:
testprog tmp/file1.txt
I get:
Cannot open directory 'tmp/file1.txt'
because that's a file rather than a directory (if you're sneaky, you can attempt to use diropen(dirname(v[1]))
if the initial diropen
fails).
这篇关于使用C打开目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!