【问题标题】:Getting directory and directorates of a given path or use current working directory if no path is given获取给定路径的目录和目录,如果没有给出路径,则使用当前工作目录
【发布时间】:2013-10-18 22:27:23
【问题描述】:

我有以下程序正在运行,但问题是它仅在给出路径时才有效。如果没有给出路径,我正在尝试找到一种方法来设置当前工作目录的路径。为此,我正在使用 char *cdir = getcwd(0,0);我需要找到一种方法将其设置为 argv,以便它指向该路径而不是 null。谁能检查我的代码并告诉我我做错了什么。我正在使用 unix 系统来编译它。

#include <dirent.h>
#include <sys/stat.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <dirent.h>
#include <unistd.h>


typedef struct stat Sub;
typedef struct dirent Dir;


void skimPath(const char *);

main(int argc, char *argv[])
{
    int i;
    Sub path;
    char *cdir = getcwd(0,0);

    if (argc <= 1)
    {
       /*
       this is the part i'm having trouble with, everything else works. I need a way to set  
       the path that is in cdir, to argv, so that it would work just like the case below      
       where argc is more than 2
       */

        argv = &cdir;
        printf("%s",argv);
        for (i = 1; i < argc; i++)
        {
            if (stat(*(argv + i), &path) == -1)
            {
                printf("WROTH PATH, DIRECTORY NOT FOUND \n%s\n", *(argv + i) ); 
                continue; 
            }

            if (S_ISDIR(path.st_mode)) 
                skimPath(*(argv + i));
        }
    }

    if (argc >= 2)
    {

        for (i = 1; i < argc; i++)
        {
            if (stat(*(argv + i), &path) == -1)
            {
                printf("WROTH PATH, DIRECTORY NOT FOUND \n%s\n", *(argv + i) ); 
                continue;
            }

            if (S_ISDIR(path.st_mode)) 
                skimPath(*(argv + i));

        }
    }
}


void skimPath(const char *dirName)
{
    char str[100];
    DIR *dir;
    Sub path;
    Dir *d;
    if ((dir = opendir(dirName)) == NULL)
    {
        printf(str, "File or Directory Could Not Open");
    }

    while ((d = readdir(dir)) != NULL)
    {
        // check if directory is d or d's paren   
        if (strcmp(d->d_name, ".") == 0 || strcmp(d->d_name, "..") == 0) 
            continue; // if ture rest will be ignored from while loop

        // saves in a buffer pointed by str
        sprintf(str, "%s/%s", dirName, d->d_name);


        if (stat(str, &path) == -1)
        {
            continue;
        }

        //checks to see if its a d
        if (S_ISDIR(path.st_mode))
        {
            printf("%s \n",d->d_name);

            // directory goes in str
            skimPath(str);

        }
    }   
}

【问题讨论】:

标签: c


【解决方案1】:

我们可以分析您的代码,但您尝试做的事情相当奇怪(详细地说,我认为还有其他方法可以做您想做的事情)。

main(int argc, char *argv[])
{
    int i;
    Sub path;
    char *cdir = getcwd(0,0);

因为你并不总是使用cdir,你可以——应该——在你使用它的块中声明它。 getcwd() 是一个昂贵的功能,特别是如果您有多个挂载的文件系统要处理,尤其是 NFS 挂载的文件系统。

    if (argc <= 1)
    {
       /*
       this is the part i'm having trouble with, everything else works. I need a way to set  
       the path that is in cdir, to argv, so that it would work just like the case below      
       where argc is more than 2
       */

        argv = &cdir;

此声明是“合法的”,但您尚未考虑后果。现在,argv 正好指向一个字符串(指针列表中没有空终止符),argc 现在不重要了。

        printf("%s",argv);

这是错误的;它应该是以下几行之一:

printf("%s\n", argv[0]);
printf("%s\n", *argv);
printf("%s\n", cdir);

您已经删除了原始参数列表,剩下的唯一参数是当前目录。

        for (i = 1; i < argc; i++)
        {

由于argv 现在指向cdir,因此您无法遍历参数。双重的,你不能从索引 1 开始这样做。

            if (stat(*(argv + i), &path) == -1)

是的,你可以这样写argv[i],但你为什么要这样做呢?

            {
                printf("WROTH PATH, DIRECTORY NOT FOUND \n%s\n", *(argv + i) ); 
                continue; 
            }

虽然您会在一本像样的字典中找到“愤怒”(“adj (archaic):anger”),但您的意思可能是“错误的”。对人大喊大叫是不友善的。此外,错误消息最好打印为标准错误;这就是它的用途。如果您使用else(或else if),则可以避免使用continue

            if (S_ISDIR(path.st_mode)) 
                skimPath(*(argv + i));
        }
    }

这么多还可以。

    if (argc >= 2)
    {
        ...
    }

我会将其写为当前代码结构的else 子句。

如果用户显式传递名称 . 作为参数,您将执行相同的操作,因此如果用户没有提供当前目录作为第一个参数,那么通过提供当前目录作为第一个参数是非常诱人的。因为当你输入main()时,条件argv[argc] == NULL为真,你其实可以这样写:

int main(int argc, char **argv)
{
    if (argc == 1)
        argv[argc++] = ".";

    assert(argc > 1);
    for (int i = 1; i < argc; i++)
    {
        ...code from the if (argc >= 2) part of your code...
    }
    return 0;
}

如果您需要插入多个参数,则必须经历更多的繁琐,更像是:

if (argc < XXX)
{
    static char *alt_argv[] = { 0, "xyz", "pqr", "abc", 0 };
    alt_argv[0] = argv[0];
    argv = alt_argv;
    argc = (sizeof(alt_argv) / sizeof(alt_argv[0])) - 1;
}

尽管有其他人的警告,argcargvmain() 函数中的局部变量,可以(小心)修改。修改argv[argc] 中的数据更接近狡猾,但这取决于您的代码是使用空指针哨兵还是使用计数。如果您使用计数并且从不访问超出(修改的)argv 数组末尾,那么您会没事的。如果您确实超出了最后的访问权限,那么您就是在践踏(或读取)大多数 Unix 变体上的环境变量。

如果您确实决定要使用当前目录的绝对路径名,那么您仍然可以调整我概述的方案来使用它。假设您在 Linux 或 BSD 衍生平台上工作,您的 getcwd() 版本将在给定空指针时分配内存,因此您可以这样写:

if (argc == 1)
    argv[argc++] = getcwd(NULL, 0);

唯一需要注意的是空指针:

for (i = 1; i < argc && argv[i] != NULL; i++)
    ...

当您需要在现实生活中完成这项工作而不是练习基本的系统调用时,请考虑使用nftw() 为您遍历目录层次结构。

【讨论】:

  • +1 以获得惊人的答案。我是建议不要修改 argv 的人,但我并不是说它不可行 - 只是它需要小心,这使得在这种情况下它可能不值得,除非有人提供详细的操作方法:-)
猜你喜欢
  • 1970-01-01
  • 2014-03-10
  • 2015-08-22
  • 2019-01-27
  • 2012-04-12
  • 2010-12-14
  • 1970-01-01
  • 2019-02-18
  • 1970-01-01
相关资源
最近更新 更多