some time ago i wrote a small post about how to check if file exists
the code is using open() but today i got a comment that i should use stat() so i read the man file and tried the next.
The question is :
is it good enough explanation and is it the right approach ?
Code:/************************************************************************ * * Purpose: This program will demonstrate the use of stat() on linux * * Author: Jabka Atu * * Date: 13 October 2007 * * * Notes: I used M J Leslie's orignal example to learn and * used his file as skelton for this * * ************************************************************************/ #include <sys/stat.h> /* declare the 'stat' structure */ #include <sys/types.h> #include <unistd.h> #include <stdio.h> /* printf */ #include <time.h> #define FILENAME "/tmp" /* PUT YOUR FILE NAME HERE */ /************************************************************************/ void file_stat(char * filename); main() { file_stat(FILENAME); } void file_stat(char * filename) { struct stat stat_p; /* 'stat_p' is a pointer to a structure * of type 'stat'. */ /* Get stats for file and place them in * the structure. */ /* To use Macro you should do the next: write the macro and as it argument use the defined types for example: Macro = S_ISDIR(mode) Argumant = mode usage: S_ISDIR(stat_p.st_mode); // st_mode is a predifined field now the MACROs for state are (thnx to http://linux.die.net/man/2/stat ) S_ISREG(m) is it a regular file? S_ISDIR(m) directory? S_ISCHR(m) character device? S_ISBLK(m) block device? S_ISFIFO(m) FIFO (named pipe)? S_ISLNK(m) symbolic link? (Not in POSIX.1-1996.) S_ISSOCK(m) socket? (Not in POSIX.1-1996.) */ stat (filename, &stat_p); printf("This will print several tests on your file \n"); printf("The answer is in boolean \n 0 - No \n 1 - yes\n"); printf("\tIs it \n\texsits ?\t\t%d \n",S_ISREG(stat_p.st_mode)); printf("\tDirectory ? \t%d \n",S_ISDIR(stat_p.st_mode)); printf("\tCharecter Device \t%d\n",S_ISCHR(stat_p.st_mode)); printf("\tblock device? \t%d\n",S_ISBLK(stat_p.st_mode)); printf("\tFIFO (named pipe)? \t%d \n",S_ISFIFO(stat_p.st_mode)); printf("\tsocket? \t\t%d\n",S_ISSOCK(stat_p.st_mode)); } /************************************************************************/


