0

As far as I know, using system() on the program is like typing on the terminal, and if I put on the terminal cd Desktop it sets the directory to the desktop as it should.

So I am trying to set a directory like system(cd ~/Desktop); or system(cd Desktop);, so then execute a file typing ./theFileName, but it isn't working. And if after that I put system(ls); it shows the files of the directory that this program itself is.

PD: I am on mac

drescherjm
  • 10,365
  • 5
  • 44
  • 64
Ilan15
  • 27
  • 4
  • You can''t do it using more than 1 system() call. Each call of system() is independent. – drescherjm Apr 20 '20 at 01:19
  • You need to change the current working directory for your program - that may (possibly will, depending on the host system) be inherited by child processes subsequently created using `system()`. Catch is, the techniques vary between implementations (host and compiler). – Peter Apr 20 '20 at 01:24

2 Answers2

1

system spawns a new shell session every time you run it, so your cwd isn't maintained between functions. You can either provide the full path like ~/Desktop/theFileName, or use a semicolon like cd ~/Desktop; ./theFileName.

Aplet123
  • 33,825
  • 1
  • 29
  • 55
0

The command you provide in system() is executed by a new shell that is launched at this occasion.
The cd command is executed by this shell but that doesn't change anything for your process that lauched the shell.

In order to actually change the current directory for your process, you need the chdir() system call.
( https://linux.die.net/man/2/chdir )

prog-fh
  • 13,492
  • 1
  • 15
  • 30