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

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

WBOY
WBOYOriginal
2016-06-07 15:49:581244browse

最近看到一个函数,第一觉得很sb,因为remove的定义在if内部,变成了局部变量,结果如果文件“234.bin”不存在的话,一定会出错的,因为remove的生存期有限。 结果,亮瞎我的: #includeiostream#include unistd.h#include stdio.h#include stdlib.husing na

最近看到一个函数,第一眼觉得很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<strong>结果各种悲剧,无论这个文件是否存在:</strong>
<p><img  src="/inc/test.jsp?url=http%3A%2F%2Fmy.csdn.net%2Fuploads%2F201206%2F07%2F1339078989_9217.jpg&refer=http%3A%2F%2Fblog.csdn.net%2Femaste_r%2Farticle%2Fdetails%2F7643479" alt="C++(五) access函数判断文件是否存在" ></p>
<p><br>
</p>
<p>事实上,我个人认为这个问题出在这个access函数的返回值上,它的返回值是</p>
<p>0    如果文件是指定的mode<br>
</p>
<p>-1   如果出错</p>
<p>所以上述程序,无论是找到文件(0),还是找不到(-1),都是false,所以应该是永远都进不了if(remove)的。。<br>
</p>
<p>所以应该是:</p>
<pre class="brush:php;toolbar:false">if(0 == access("234.bin",F_OK))
{
remove = true;
}
这么改后,还是没能看到我想要的错误,我想要看到remove不存在的出错啊~~很可惜,依旧是:

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

原来:

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<strong>总结:</strong>
<p>(一)用access函数注意返回值是 0 和-1,都是false<br>
</p>
<p>(二)remove是个函数名,定义命名的时候注意不要用到系统的东东<br>
</p>
<br>


</iostream>
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn