Sign in to follow this  
Ksingh30

C and Unix

Recommended Posts

Sneftel    1788
The POSIX function getcwd() will give you the current working directory. Read the documentation before using it, as it can be unsafe.

Share this post


Link to post
Share on other sites
oatz01    124

#include<unistd.h>

int main(void)
{
char mystring[100];

getcwd(mystring);

return 0;
}



The getcwd() function puts the name of the current working directory into a char *. Make sure to #include<unistd.h> and make sure mystring has enough space to hold the name. Type 'man 3 getcwd' on your terminal for more info.

Share this post


Link to post
Share on other sites
Ksingh30    100
that didnt work.
I tried this

char* getpath()
{
char *T;
getcwd(T);
return T;
}

and I got the following errors:
error: too few arguments to function ‘char* getcwd(char*, size_t)’

I guess it also wants some size.

Share this post


Link to post
Share on other sites
Oluseyi    2103
That won't work either, erissian. The memory assigned to T is allocated locally, and will be deallocated when the call boundary is crossed (ie, when the function returns). You end up returning a pointer to memory that is no longer "valid."

bool getpath(char **out, int max_len)
{
return 0 == getcwd(*out, max_len);
}

If you can figure out how that code works, then you know enough to use getcwd safely. If not, you don't.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this