How to check if a file exists in c [duplicate]

2019-06-23 23:17发布

问题:

This question already has an answer here:

  • What's the best way to check if a file exists in C? 9 answers

I have core files generated with the pid attached to its name or sometimes only the name core. I need to check if a file exists with name core.pid or core. I have tried using stat() where I used the path string as /tmp/core*, but failed. Can you please let me know how to solve this.Thanks for your time.

回答1:

Since you're using Linux, you can use

http://man7.org/linux/man-pages/man3/glob.3.html

glob will read a directory and return a list of names matching a pattern, which is just what you want.

You also might want to use http://man7.org/linux/man-pages/man7/inotify.7.html to only read the directory when it changes.



回答2:

You can use the access function:

if (0 == access(path, 0)) { 
    file exists;
} 
else { 
    file does not exist;
}


回答3:

Looks like this has been answered before. While stat() is acceptable, if you're only checking for existence, I would use access() (docs)



回答4:

If you only want to check whether a new file has appeared, use the <dirent.h> API (opendir(), readdir(), etc.) to obtain a list of files in the directory in question before and after the crash, then compare the two lists to see if there are more files after the second check, and if so, which one it is.



回答5:

You should just stat() both possible names, core.pid and core, and see if either one (or both) exist.

Your attempt to stat() /tmp/core* suggests that you are expecting stat() to accept a shell glob pattern. Shell glob patterns are not accepted by any system calls. There is a C library function fnmatch which allows you to resolve them, and you could use that... but in this case since you are just checking for two different filenames it's easier and more efficient to just check them both one at a time.

EDIT: if you do not know the actual filename in advance but you only know that it starts with core. and is followed by a number, then you will have to open the directory with opendir, enumerate all the files in it with readdir, and see if any one of them matches the desired pattern (you could use fnmatch for this, or just parse it manually).



回答6:

I believe the simple way is to use fopen().

FILE *fp;

// fopen won't work on "r" mode if file doesn't exist
fp = fopen("core.pid","r");

if(fp == NULL){
    // File doesn't exist
    ...
}else{
    // File does exist
    ...
}


回答7:

If the second argument is F_OK, access simply checks for the file’s existence. If the file exists, the return value is 0; if not, the return value is –1 and errno is set to ENOENT. Note that errno may instead be set to EACCES if a directory in the file path is inaccessible.

From the book "Advanced Linux Programming".