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

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth

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

Disclosure: My content contains affiliate links.

43,693 questions

57,001 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 387 views
2 answers 268 views
1 answer 259 views
1 answer 401 views
2 answers 343 views
...