我有以下程序正在运行,但问题是它仅在给出路径时才有效。如果没有给出路径,我正在尝试找到一种方法来设置当前工作目录的路径。为此,我正在使用 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);
}
}
}