LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Current dir in C (https://www.linuxquestions.org/questions/programming-9/current-dir-in-c-467493/)

rigel_kent 07-25-2006 11:47 AM

Current dir in C
 
Hi,

Does anyone know how to get the current working directory within a C program?

Kind regards,

Rigel_Kent

tuxdev 07-25-2006 12:03 PM

Try getcwd(). You will can either do it the most correct way, by allocating a dynamic string, and expanding it if getcwd() truncates. You may be able to use a statically allocated string of length PATH_MAX, but that isn't as guaranteed

paulsm4 07-25-2006 12:04 PM

man getcwd
Quote:

NAME
getcwd, get_current_dir_name, getwd - Get current working
directory

SYNOPSIS
#include <unistd.h>

char *getcwd(char *buf, size_t size);
char *get_current_dir_name(void);
char *getwd(char *buf);
...

rigel_kent 07-25-2006 02:33 PM

Hi,

Thanks for replying. It's solved...I used:

Code:

  int _MAX_SIZE = 128; 

  char path[_MAX_SIZE];

  getcwd (path, _MAX_SIZE);

  fprintf(file_out, "%d\n", path);

Kind regards,

Rigel_Kent

tuxdev 07-25-2006 04:30 PM

I'm not sure how that can even work, since _MAX_SIZE is not a constant compile-time expression. You are generally supposed to use #define for that in C.

The size you picked is relatively tiny so bad things happening are decently probable.

AdaHacker 07-25-2006 05:17 PM

Quote:

Originally Posted by tuxdev
I'm not sure how that can even work, since _MAX_SIZE is not a constant compile-time expression. You are generally supposed to use #define for that in C.

It's not allowed by the ISO standard, but it does work. This shouldn't be too surprising, as it's pretty trivial for the compiler to convert
Code:

char path[_MAX_SIZE];
into something like
Code:

char *path;
path = malloc(_MAX_SIZE);

GCC is apparently pretty forgiving about such non-standard code. If you want to stick strictly to the standard, compile with the -pedantic option.

rigel_kent 07-25-2006 06:04 PM

Quote:

Originally Posted by tuxdev
I'm not sure how that can even work, since _MAX_SIZE is not a constant compile-time expression. You are generally supposed to use #define for that in C.

The size you picked is relatively tiny so bad things happening are decently probable.

I agree. But if I try to use _MAX_SIZE it gives me an error in the compilation. How should I use it?

Kind regards,

Rigel_Kent

paulsm4 07-25-2006 06:18 PM

PATH_MAX is usually the right constant under Linux.

EXAMPLE:
Code:

#include <stdio.h>
#include <limits.h>

int
main ()
{
  printf ("PATH_MAX= %d\n", PATH_MAX);
  return 0;
}



All times are GMT -5. The time now is 10:04 PM.