LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   file exists? (https://www.linuxquestions.org/questions/programming-9/file-exists-108620/)

raven 10-26-2003 05:38 AM

file exists?
 
Hello

I am programming c in lunux. I need to determine weather a file exists, but without opening it. Is there a way to do this?

I dont want to use open("file",0) and check the return value...

Thanks

raven

slakmagik 10-26-2003 06:09 AM

Never mind - that was bash - dunno if it works in C.

I'm an idiot.

kev82 10-26-2003 06:40 AM

look up the stat sytem call

man 2 stat

Hko 10-26-2003 07:05 AM

Code:

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>

int main(int argc, char **argv)
{
    char *filename;
    int result;
    struct stat statinfo;

    if (argc != 2) {
          fprintf(stderr, "Usage: %s [<file>]\n", argv[0]);
          return 1;
    }
    filename = argv[1];
    result = stat(filename, &statinfo);
    if (result < 0) {
          if (errno == ENOENT) {
              printf("File %s does not exist\n", filename);
              return 0;
          } else {
              perror(*argv);
              return 1;
          }
    }
    printf("File %s exists, and is a ", filename);
    switch (statinfo.st_mode & S_IFMT) {
    case S_IFREG:  printf("regular file.\n"); break;
    case S_IFSOCK: printf("filesystem socket.\n"); break;
    case S_IFLNK:  printf("symbolic link.\n"); break;
    case S_IFBLK:  printf("block device file.\n"); break;
    case S_IFDIR:  printf("directory.\n"); break;
    case S_IFCHR:  printf("character device file.\n"); break;
    case S_IFIFO:  printf("filesystem pipe (fifo) file.\n"); break;
    default:  printf("unknown type of file.\n"); break;
    }
    return 0;
}


SaTaN 10-26-2003 07:06 AM

Code:

#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
main()
{
        struct stat BUF;
        if(stat("/path/to/where/file/exists",&BUF)==-1)
        {
                printf("File doesn't exist\n");
        }
}

Hope this does it for you

Hko 10-26-2003 07:23 AM

That's not reliable.
If stat() returns -1, that doesn't necessarily mean the file does not exist.

SaTaN 10-26-2003 07:27 AM

Yeah you are right ...
You need to check errono for the correct error.

Thanks for pointing that mistake.

raven 10-26-2003 07:44 AM

Wow :-) so many replies. Thanks for all, Now I've got it :-)

raven


All times are GMT -5. The time now is 02:42 PM.