检查C中是否存在文件的最佳方法是什么?有比简单地打开文件更好的方法吗?int exists(const char *fname){
FILE *file;
if ((file = fopen(fname, "r")))
{
fclose(file);
return 1;
}
return 0;}
3 回答
炎炎设计
TA贡献1808条经验 获得超4个赞
access()unistd.h
if( access( fname, F_OK ) != -1 ) {
// file exists} else {
// file doesn't exist}R_OK, W_OKX_OKF_OKR_OK|W_OK)
更新W_OKaccess( fname, W_OK )
慕尼黑8549860
TA贡献1818条经验 获得超11个赞
int file_exist (char *filename){
struct stat buffer;
return (stat (filename, &buffer) == 0);}if (file_exist ("myfile.txt")){
printf ("It exists\n");}
回首忆惘然
TA贡献1847条经验 获得超11个赞
#include <fcntl.h>#include <errno.h>fd = open(pathname, O_CREAT | O_WRONLY | O_EXCL, S_IRUSR | S_IWUSR);if (fd < 0) {
/* failure */
if (errno == EEXIST) {
/* the file already existed */
...
}} else {
/* now you can use the file */}- 3 回答
- 0 关注
- 1104 浏览
添加回答
举报
0/150
提交
取消
