thesupergeek
thesupergeek

Reputation: 13

Get current path when C app is launched from /bin/ in Linux

So, I am working on an application that reads files, much the way vim or cat would, where you type "appname /path/to/file.txt" and it passes the file path as a perameter to the program which manipulates the file in some way.

I have run into a roadblock though. In vim, cat, or a similar program, you can type "appname file.txt", and it will read the file in the current directory that you launch the application from terminal in.

For example, I want to edit a file my documents directory. I type "cd ~/Documents", and then I can either type "vim ~/Documents/Essay.txt", or I just can type "vim Essay.txt".

My application will be stored in a binary file in the /bin/ directory so I can launch it from anywhere using the Terminal, but how do I pass the path name of the directory I am in when I call it from terminal?

As I am a new Linux developer (I have always worked with the .NET launguages in Windows) I am not sure weather this is handled by the Linux terminal, or by the C application itself.

Any help or suggestions would be much appreciated!

Also, if there is a more efficiant way to run it from the terminal than sticking it in the /bin/, let me know.

Upvotes: 1

Views: 248

Answers (2)

teppic
teppic

Reputation: 8195

If you want to get the directory the process was run from you can use the system call getcwd to copy a string into a buffer and return it. The kernel keeps track of this for every process.

e.g.

char buf[100];
printf("Current directory: %s\n", getcwd(buf, 100));

The working directory can be changed, but will default to where the process launched.

Upvotes: 1

amo
amo

Reputation: 4340

This should work just fine without you having to do anything special. Did you try something that didn't work as you expected?

Generally you don't put user programs in /bin. I would store your program in /usr/local/bin.

https://unix.stackexchange.com/a/8658

Upvotes: 0

Related Questions