您的位置:首页 > 编程语言 > C语言/C++

C++ access函数判断文件是否存在

2014-01-07 09:57 465 查看
最近看到一个函数,第一眼觉得很sb,因为remove的定义在if内部,变成了局部变量,结果如果文件“234.bin”不存在的话,一定会出错的,因为remove的生存期有限。

结果,亮瞎我的眼:

[cpp] view
plaincopy

#include<iostream>

#include "unistd.h"

#include "stdio.h"

#include "stdlib.h"

using namespace std;

int main()

{

if(access("234.bin",F_OK))

{

bool remove=true;

}

if(remove)

{

cout<<"Need to delete..."<<endl;

}

return 0;

}

结果各种悲剧,无论这个文件是否存在:



事实上,我个人认为这个问题出在这个access函数的返回值上,它的返回值是

0 如果文件是指定的mode

-1 如果出错

所以上述程序,无论是找到文件(0),还是找不到(-1),都是false,所以应该是永远都进不了if(remove)的。。

所以应该是:

[cpp] view
plaincopy

if(0 == access("234.bin",F_OK))

{

remove = true;

}

这么改后,还是没能看到我想要的错误,我想要看到remove不存在的出错啊~~很可惜,依旧是:



原来:

remove是一个已经存在的函数,函数地址不为空,所以一直都能进 if(remove){}

大家,以后判断文件是否存在,用以下的代码比较好:

[cpp] view
plaincopy

#include<iostream>

#include "unistd.h"

#include "stdio.h"

#include "stdlib.h"

using namespace std;

int file_exist(char *file)

{

return (access(file,F_OK) == 0);

}

int main()

{

cout<<"Does file exist :"<<(file_exist("234.bin")?"Yes":"No")<<endl;

return 0;

}

总结:

(一)用access函数注意返回值是 0 和-1,都是false

(二)remove是个函数名,定义命名的时候注意不要用到系统的东东
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: