For my second project in C we have to write a program to take in 2 arguments, one being a directory path and another being an int level_val. If level_val is -1, files in the parent
directory are to be listed, and so on up the directory tree for -2, -3, etc.
For a positive value k, say, all files are to be listed which are in
directories exactly k subdirectory steps below path_to_start.
I dont know how to parse in the command argument level_val as an int, what i was thinking i could do was just if negative then call chdir("..") in a for loop up to negative value of level_val. Not sure what to do with the positive though...
Anyway, my main question is how do i parse in the argument level_val and store as an int to work in the program? here is my code so far, all it does is print directory path supplied, my code is incomplete because things that i was working on are still in it:
Sorry the clutter in the code, just me testing various things, as you can see I am new to C and how things work.
Thanks in advance for any help.
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <string.h>
#include <unistd.h>
#define MAX_DIR_PATH 2048
int main(int argc, char *argv[])
{
unsigned long depth;
int i = 0;
struct dirent* entry;
char cwd[MAX_DIR_PATH+1];
char* directoryPath;
DIR* dir;
// if ( argc == 3 )
// {
printf("The value of level_val is: %s\n", argv[2]);
/*DIR* dir = opendir(argv[1]);
if(!dir){
perror("opendir");
exit(1);
}*/
directoryPath = argv[1];
if (chdir(directoryPath) == -1)
{
fprintf(stderr, "Cannot change to directory '%s': ", directoryPath);
perror("");
exit(1);
}
if (!getcwd(cwd, MAX_DIR_PATH+1))
{
perror("getcwd:");
return;
}
/*if(argv[2] < 0)
{
printf("in first if\n");
while(i != argv[2])
{
printf("in here");
printf("In if\n");
if(!chdir(".."))
{
printf("in second if");
perror("chdir (1)");
exit(1);
}
i--;
}
}*/
dir = opendir(".");
if (!dir)
{
fprintf(stderr, "Cannot read directory '%s': ", cwd);
perror("");
return;
}
printf("Directory conents:\n");
while( (entry = readdir(dir)) != NULL)
{
printf("%s\n", entry->d_name);
}
printf("new working directory\n");
printf("Directory conents:\n");
while( (entry = readdir(dir)) != NULL)
{
printf("%s\n", entry->d_name);
}
/*else{
printf("Not enough arguments supplied to run program.");
}*/
system("PAUSE");
return 0;
}