1

I am writing a program that is similar to the "cd" command but uses shortcuts.

(to save a path: cds -s 1 C:\saved\directory\path) (to switch to a saved path: cds 1)

To do this I have tried both chdir() and system() but the effect only lasts as long as the program is running. Once the program terminates the path is restored to what it was before the program was run. I am currently using a work-around by loading my program with a bat file which runs another bat file(that contains the cd command) which was created by the program.

so my bat file is similar to:

cds.exe %1 %2 %3
C:\temp\cds_cmd.bat
del C:\temp\cds_cmd.bat

cds_cmd.bat is generated by cds.exe

I would really like to know if there is any other way I could do this without using bat files.

I found and read Is there any way to change directory using C language? but did not find what I was looking for.

Community
  • 1
  • 1
  • 1
    See the comments on the accepted answer on the question you've linked to - they explain why you can't do this. – Philip Kendall Apr 10 '13 at 21:00
  • You could cut it down to one batch file by setting an environment variable like CD_PATH in the C .exe, then replace the `cds_cmd.bat` stuff with `cd %CD_PATH%` – AjV Jsy Apr 10 '13 at 21:25
  • Thank you Fuzzy, that would be a much better solution than what I currently have but it seems it has a problem similar to my original problem http://stackoverflow.com/questions/3416638/set-environment-variables-in-c – user2267867 Apr 10 '13 at 23:10
  • I haven't tried it, but I wonder if you could get your C prog to call another batch file designed to set the env. var. using SetX? (http://stackoverflow.com/questions/3803581/setting-a-system-environment-variable-from-a-windows-batch-file) i.e. have a `setvar.bat` containing something like `setx %1=%2` which your C prog would silently call with `CD_PATH` and `C:\somepath` as params? Worth playing with? :) – AjV Jsy Apr 11 '13 at 09:25
  • Also, a trick I used to use back in the day, was to rewrite the batch file while it was running :) .... my batch file called a Turbo Pascal prog which rewrote the same batch file as it was halfway through being interpreted by DOS, and the pascal .com added what it needed to add. DOS got a bit upset if the new batch wasn't the same size as the old one up to the point where it needed to fetch the next line, so the trick was to pad things out so the same commands were always in the same place. It worked well in the end! – AjV Jsy Apr 11 '13 at 09:30

1 Answers1

0

This is not an answer for your C problem, but an alternative solution using Batch only:

To save a path:

set 1=C:\saved\directory\path

To switch to a saved path:

cd %1%

You may use different variable names (not numbers) for this purpose, if you wish.

Aacini
  • 65,180
  • 12
  • 72
  • 108