现在的位置: 首页 > 综合 > 正文

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

2013年01月21日 ⁄ 综合 ⁄ 共 888字 ⁄ 字号 评论关闭

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

结果,亮瞎我的眼:

#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)的。。

所以应该是:

if(0 == access("234.bin",F_OK))
{
remove = true;
}

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

原来:

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

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

#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是个函数名,定义命名的时候注意不要用到系统的东东

抱歉!评论已关闭.