2

I have tried using chdir and cd but and ran dir but both displayed the directory of the folder/project folder i am in. Following is the source Code

system("chdir (C:/)");
system("dir");

and this

system("chdir C:/");
system("dir");

and this

system("cd C:/");
system("dir");
Zimad
  • 343
  • 1
  • 5
  • 13

4 Answers4

3

You can use the Posix chdir function to change directory and then the Posix opendir, readdir and closedir methods to enumerate the contents of the directory.

Both of these questions have been covered before on SO. Please refer to:

Change current working directory C

How do you get a directory listing in C?

Community
  • 1
  • 1
Andy Brown
  • 11,766
  • 2
  • 42
  • 61
3

by calling system() you are creating a sub process that will change directories but not your current process working directory.

try calling the function chdir as this post suggests: Change the current working directory in C++

Community
  • 1
  • 1
Rob
  • 2,618
  • 2
  • 22
  • 29
1

AFAIK, by calling system() function call, it will execute the command by calling /bin/sh -c and will return the exit status. The next call to system() will invoke another /bin/sh -c.

So, basically, for each call, a new child shell is used. Hence, you cannot expect the result of the first call to be preserved [persistent] in the second call. Your current process directory will not be affected. Next call to system() will consider the old current process directory itself.

You can try providing both the commands to be executed in a single call to system(), by joining them with && or ;

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
1

I think you shouldn't use system() as it makes you program non-portable. (dir doesn't exist on Linux, for exemple)

You may use opendir and readdir in order to open a directory and list the files it contains.

Here is a simple example :

DIR *dp;
struct dirent *dptr;
if(NULL == (dp = opendir("C:")) )
{
    perror("Opendir");
    exit(EXIT_FAILURE);
}
else
{
    while(NULL != (dptr = readdir(dp)) )
    {
        printf("%s ",dptr->d_name);
    }
    closedir(dp);
}
Chostakovitch
  • 965
  • 1
  • 9
  • 33
  • How would that change the program's current work directory? – alk Dec 24 '14 at 14:23
  • It doesn't, that's just a different approch because he doesn't need to change the directory. This is another way to do the same thing : display the content of a directory. – Chostakovitch Dec 24 '14 at 14:26