最近看到一个函数,第一觉得很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<<"Need to delete..."<<endl;
}
return 0;
}

事实上,我个人认为这个问题出在这个access函数的返回值上,它的返回值是
0 如果文件是指定的mode
-1 如果出错
所以上述程序,无论是找到文件(0),还是找不到(-1),都是false,所以应该是永远都进不了if(remove)的。。
所以应该是:
立即学习“C++免费学习笔记(深入)”;
if(0 == access("234.bin",F_OK))
{
remove = true;
}
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是个函数名,定义命名的时候注意不要用到系统的东东
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号