How to get the current directory Using a C program




c programming
c programming
c programming
c programming

C – How do I get the directory that a program is running from?

In this Tutorial We will learn how to print the path of current working directory. The code below is applicable for both Linux and window. we just need to define the flags for current operating system.

By default the code will run as it is on Linux. if we want to use it on Windows , uncomment the line 2.

C Program to print current working directory

/* 'pwd' to get path to the current file in C Program */

#include <stdio.h>  /* defines FILENAME_MAX */
//#define WINDOWS  /* uncomment this line to use it for windows.*/
#ifdef WINDOWS
#include <direct.h>
#define GetCurrentDir _getcwd
#else
#include <unistd.h>
#define GetCurrentDir getcwd
#endif

int main(){
  char buff[FILENAME_MAX];
  GetCurrentDir( buff, FILENAME_MAX );
  printf("Current working dir: %s\n", buff);
  return 1;
}
/*
OUTPUT:
Current working dir: /home/your_dir_name
*/

 

 


Partner Sites

VideoToGifs.com

EasyOnlineConverter.com

SqliteTutorials.com





Be the first to comment

Leave a Reply

Your email address will not be published.


*