C语言 使用 C 打开目录

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3554120/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 06:17:03  来源:igfitidea点击:

Open directory using C

copendir

提问by Vinod K

I am accepting the path through command line input.

我正在接受通过命令行输入的路径。

When I do

当我做

dir=opendir(args[1]);

it doesn' t enter the loop...i.e dir==null...

它没有进入循环...即dir==null...

How do I pass the command line input to dir pointer?

如何将命令行输入传递给 dir 指针?

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

回答by paxdiablo

You should really post your code(a), but here goes. Start with something like:

你真的应该发布你的代码(a),但这里是。从以下内容开始:

    #include <stdio.h>
    #include <dirent.h>

    int main (int argc, char *argv[]) {
        struct dirent *pDirent;
        DIR *pDir;

        // Ensure correct argument count.

        if (argc != 2) {
            printf ("Usage: testprog <dirname>\n");
            return 1;
        }

        // Ensure we can open directory.

        pDir = opendir (argv[1]);
        if (pDir == NULL) {
            printf ("Cannot open directory '%s'\n", argv[1]);
            return 1;
        }

        // Process each entry.

        while ((pDirent = readdir(pDir)) != NULL) {
            printf ("[%s]\n", pDirent->d_name);
        }

        // Close directory and exit.

        closedir (pDir);
        return 0;
    }

You need to check in your case that args[1]is both set and refers to an actual directory. A sample run, with tmpis a subdirectory off my current directory but you can use any valid directory, gives me: testprog tmp

您需要检查args[1]已设置并引用实际目录的案例。一个示例运行,它tmp是我当前目录下的一个子目录,但您可以使用任何有效目录,给我:testprog tmp

[.]
[..]
[file1.txt]
[file1_file1.txt]
[file2.avi]
[file2_file2.avi]
[file3.b.txt]
[file3_file3.b.txt]

Note also that you have to pass a directoryin, not a file.When I execute:

另请注意,您必须传入目录,而不是文件。当我执行:

testprog tmp/file1.txt

I get:

我得到:

Cannot open directory 'tmp/file1.txt'

That's because it's a file rather than a directory (though, if you're sneaky, you can attempt to use diropen(dirname(argv[1]))if the initial diropenfails).

那是因为它是一个文件而不是一个目录(不过,如果你偷偷摸摸,diropen(dirname(argv[1]))如果初始diropen失败,你可以尝试使用)。



(a)This has now been rectified but, since this answer has been accepted, I'm going to assume it was the issue of whatever you were passing in.

(a)现在已经更正了,但是,由于这个答案已被接受,我将假设这是您传入的任何问题。

回答by Thanatos

Some feedback on the segment of code, though for the most part, it should work...

关于代码段的一些反馈,但在大多数情况下,它应该可以工作......

void main(int c,char **args)
  • int main- the standard defines mainas returning an int.
  • cand argsare typically named argcand argv, respectfully, but you are allowed to name them anything
  • int main- 标准定义main为返回一个int.
  • c并且args通常被命名为argcand argv,恭敬地,但你可以给他们起任何名字

...

...

{
DIR *dir;
struct dirent *dent;
char buffer[50];
strcpy(buffer,args[1]);
  • You have a buffer overflow here: If args[1]is longer than 50 bytes, bufferwill not be able to hold it, and you will write to memory that you shouldn't. There's no reason I can see to copy the buffer here, so you can sidestep these issues by just not using strcpy...
  • 这里有一个缓冲区溢出:如果args[1]超过 50 个字节,buffer将无法保存它,并且您将写入不应该写入的内存。我没有理由在此处复制缓冲区,因此您可以通过不使用strcpy...

...

...

dir=opendir(buffer);   //this part

If this returning NULL, it can be for a few reasons:

如果返回NULL,可能有以下几个原因:

  • The directory didn't exist. (Did you type it right? Did it have a space in it, and you typed ./your_program my directory, which will fail, because it tries to opendir("my"))
  • You lack permissions to the directory
  • There's insufficient memory. (This is unlikely.)
  • 该目录不存在。(你打对了吗?里面有空格吗,你输入了./your_program my directory,这会失败,因为它试图opendir("my")
  • 您缺乏对目录的权限
  • 内存不足。(这不太可能。)

回答by Anil Vishnoi

Parameters passed to the C program executable is nothing but an array of string(or character pointer),so memory would have been already allocated for these input parameter before your program access these parameters,so no need to allocate buffer,and that way you can avoid error handling code in your program as well(Reduce chances of segfault :)).

传递给 C 程序可执行文件的参数只不过是一个字符串数组(或字符指针),因此在您的程序访问这些参数之前,已经为这些输入参数分配了内存,因此无需分配缓冲区,这样您就可以避免程序中的错误处理代码(减少段错误的机会:))。

回答by Vijay S B

Here is a simple way to implement lscommand using c. To run use for example ./xls /tmp

这是ls使用c. 例如运行使用./xls /tmp

    #include<stdio.h>
    #include <dirent.h>
    void main(int argc,char *argv[])
    {
   DIR *dir;
   struct dirent *dent;
   dir = opendir(argv[1]);   

   if(dir!=NULL)
      {
   while((dent=readdir(dir))!=NULL)
                    {
        if((strcmp(dent->d_name,".")==0 || strcmp(dent->d_name,"..")==0 || (*dent->d_name) == '.' ))
            {
            }
       else
              {
        printf(dent->d_name);
        printf("\n");
              }
                    }
       }
       close(dir);
     }