0

I have function:

gint isfileexists(gchar *filename) 
{
struct stat buffer; 
gint i = stat(filename, &buffer);
if (i == 0) {
   return 1;
}
return 0;
}

and if I call them:

isfileexists("/etc/myfile")

it search "myfile" in "/home/user/etc/myfile". How to do this well?

yulian
  • 1,601
  • 3
  • 21
  • 49
Nips
  • 13,162
  • 23
  • 65
  • 103
  • What is `gint`, `gchar`? And are you sure that's how you're calling it, and that's what it's doing? – Dave Aug 04 '13 at 22:45
  • gint and gchar is from glib: https://developer.gnome.org/glib/ – Nips Aug 04 '13 at 22:47
  • You'll have to use `const char *home = getenv("HOME");` to find the value of `$HOME` and then prepend that to the file name you're given. Otherwise, it will look in the system's `/etc` directory for `myfile` and probably won't find it. – Jonathan Leffler Aug 04 '13 at 22:50

1 Answers1

3

It should only look for /home/USER/etc/myfile if:

  • you leave off the leading / when calling isfileexists; and
  • that directory /home/USER is your current working directory.

In other words, if the argument is a relative path name.

Since you have the leading /, it will be an absolute path name and should access /etc/myfile.

If I've misunderstood and you actually want the one in your home directory, you can use getenv("HOME") to get your home directory and then append /etc/myfile with strcat. That will also work regardless of your current working directory.

paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953