Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Linux by (18.4k points)
I am making the C program where I need to get a directory that this program is started from. This program is written on UNIX computers. I have been looking at the opendir() and telldir(), but the telldir() returns the off_t (long int), but it doesn't help me.

How can I get a current path in the string (char array)?

1 Answer

0 votes
by (36.8k points)

Have you had the look at getcwd()?

#include <unistd.h>

char *getcwd(char *buf, size_t size);

Simple example:

#include <unistd.h>

#include <stdio.h>

#include <limits.h>

int main() {

   char cwd[PATH_MAX];

   if (getcwd(cwd, sizeof(cwd)) != NULL) {

       printf("Current working dir: %s\n", cwd);

   } else {

       perror("getcwd() error");

       return 1;

   }

   return 0;

}

Come and join Linux training to gain great knowledge. 

Do check out the video below

 

 

Related questions

0 votes
1 answer
asked Dec 1, 2020 in Linux by blackindya (18.4k points)
0 votes
1 answer
0 votes
1 answer
asked Nov 28, 2020 in Linux by blackindya (18.4k points)
0 votes
1 answer
asked Nov 29, 2020 in Linux by blackindya (18.4k points)

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...