Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,845 questions

51,766 answers

573 users

How to get the current working directory in C

2 Answers

0 votes
#include <unistd.h>
#include <stdio.h>
#include <limits.h>
 
int main() {
   char buf[PATH_MAX];
    
   if (getcwd(buf, sizeof(buf)) != NULL) {
       printf("%s\n", buf);
   } else {
       perror("getcwd() error");
       return 1;
   }

   return 0;
}
       
       
/*
run:
        
C:\...\test\test-project\Debug
   
*/

 



answered Jul 3, 2020 by avibootz
edited Apr 16, 2024 by avibootz
0 votes
#include <stdio.h>
#include <unistd.h> // readlink
#include <stdlib.h> // exit
#include <linux/limits.h> // PATH_MAX // exe
#include <libgen.h> // dirname

int main()
{
    char exe[PATH_MAX], real_exe[PATH_MAX];
    ssize_t r;
    char *dir;

    if ((r = readlink("/proc/self/exe", exe, PATH_MAX)) < 0) {
        exit(1);
    }
    
    if (r == PATH_MAX) {
	    r -= 1;
    }
    exe[r] = 0;
    
    if (realpath(exe, real_exe) == NULL) {
	    exit(1);
    }
    
    dir = dirname(real_exe);
    puts(dir);
    
    return 0;
}


/*
run:

/tmp/Mx3Jtkqpxp

*/

 



answered Jun 3, 2025 by avibootz

Related questions

1 answer 281 views
2 answers 105 views
1 answer 104 views
1 answer 248 views
2 answers 194 views
...