Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Best way to get pwd from portable C code 1

Status
Not open for further replies.

SkiLift

Programmer
Dec 18, 2003
47
US
Is the code below actually the best way to get the present working directory? The code must be portable to many flavors of Unix and Windows. The code works, but is very long for a simple thing.
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define WIN

#ifdef UNIX
#include <strings.h>
#endif

main()
{
  FILE *fp;
  char str[100], *cmd;

#ifdef UNIX
  cmd = "pwd >pwd.out";
#else
  cmd = "cd >pwd.out";
#endif

  system(cmd);
  fp = fopen("pwd.out", "r");
  fgets(str, 100, fp);
  fclose(fp);
  str[strlen(str)-1] = '\0';	// get rid of newline.
  printf("%s\n", str);
}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top