0

I am running the following program, which checks if a file exists or not using stat(). But, when I am passing a path say, $HOME/file.sh, it fails with ENOENT error. But when I pass the expanded path i.e. /root/file.sh, stat() returns success i.e. exit code 0.

int main ()
{
    struct stat statbuf;
    char path [1024];
    strcpy(path,"$HOME/file.sh");

    int rc = stat(path,&statbuf);

    if (rc == -1 )
    {
        printf ("File not found !!\n");
    }
    else
        printf("Found it !!\n");

    return 0;
}
timrau
  • 22,578
  • 4
  • 51
  • 64
trax_code
  • 19
  • 1
  • 4
  • 1
    $HOME has meaning to shell scripts, but not C programs. You are asking stat to look for a file named file.sh in a directory named $HOME which is below your current working directory. – Scooter Sep 18 '12 at 14:07

1 Answers1

4

strcpy() will not expand the environment variable $HOME to its value, but will copy the extract string literal as specified. You can obtain the value of $HOME using getenv().

Change your failure message to:

printf("File not found: %s\n", path);

for confirmation.

hmjd
  • 120,187
  • 20
  • 207
  • 252
  • Yes, but that is not my concern. I could have directly passed $HOME/file.sh to stat. but my question is do I need to pass an absolute path to stat ? – trax_code Sep 18 '12 at 13:27
  • @trax_code, no you do not. If the path is not absolute then the path is treated as a relative path and it will be relative to the current directory of the process. – hmjd Sep 18 '12 at 13:31
  • ok. one question. By current directory, you mean the directory from where i am running the executable ? – trax_code Sep 18 '12 at 13:43
  • @trax_code, yes. You can obtain the current directory of your process using [`getcwd()`](http://linux.die.net/man/3/getcwd) if you would like to display for diagnostic purpose. – hmjd Sep 18 '12 at 13:47
  • 1
    `stat()` doesn't expand the env/ var/ `$HOME` neither. Expansion is done by the shell, and `stat()` won't use the shell. @trax_code – alk Sep 18 '12 at 14:12