access判断文件是否存在(写入文件过程中拔掉存储卡)

it2025-09-23  6

 一、背景

在测试写文件过程中拔掉存储卡,access函数判断文件是否存在,能否正常写入文件。

二、测试

使用到的函数以及头文件

#include <iostream> #include <stdio.h> #include <unistd.h> #include <limits.h> using namespace std; std::string GetFilePathByFd(FILE* fp) { if(fp == NULL){ return ""; } int fd=-1; fd = fileno(fp); if (0 >= fd) { return std::string (); } char buf[1024] = {'\0'}; char file_path[PATH_MAX] = {'0'}; // PATH_MAX in limits.h snprintf(buf, sizeof (buf), "/proc/self/fd/%d", fd); if (readlink(buf, file_path, sizeof(file_path) - 1) != -1) { return std::string (file_path); } return std::string (); }

 测试案例1:

在写入文件过程中,拔掉卡,文件还是存在的,但是已经没有那个目录了,证明该文件存在系统缓存里面

int main() { FILE* fd = NULL; fd = fopen("/mnt/tttttt.txt","w+"); if(fd == NULL){ cout <<"open fd err " << endl; return 0; } while(1){ string fpath = GetFilePathByFd(fd); cout << fpath <<endl; if(fpath == ""){ if(fd == NULL) cout <<"NULL"<<endl; continue; } cout << "access: " << access(fpath.c_str(), F_OK) <<endl; if(0!=access(fpath.c_str(), F_OK)){ fclose(fd); fd = NULL; cout << "file not exist" <<endl; }else{ cout << " file exist" <<endl; } fwrite("123",3,1,fd); fflush(fd); sleep(1); } fclose(fd); }

 

 测试案例2:

拔掉卡后,继续close文件,可以看到成功关闭文件,但是文件还在缓存里面,需要重新挂载卡后(保证也是挂载在原来目录下才行),刷新系统缓存才能删除系统中的缓存文件。()

int main() { FILE* fd = NULL; fd = fopen("/mnt/tttttt.txt","w+"); if(fd == NULL){ cout <<"open fd err " << endl; return 0; } int ii=10; while(ii--){ cout << "access: " << access("/mnt/tttttt.txt", F_OK) <<endl; if(0!=access("/mnt/tttttt.txt", F_OK)){ fclose(fd); fd = NULL; cout << "file not exist" <<endl; }else{ cout << " file exist" <<endl; } if(ii == 3){//打印6次前拔卡 cout << "close: " << fclose(fd) <<endl; fd = NULL; } if(fd == NULL){ continue; } fwrite("123",3,1,fd); fflush(fd); sleep(2); } }

 

 

测试案例3:

拔卡之前关闭文件 

int main() { FILE* fd = NULL; fd = fopen("/mnt/tttttt.txt","w+"); if(fd == NULL){ cout <<"open fd err " << endl; return 0; } int ii=10; while(ii--){ string fpath = GetFilePathByFd(fd); cout << fpath <<endl; if(fpath == ""){ if(fd == NULL) cout <<"NULL"<<endl; continue; } cout << "access: " << access(fpath.c_str(), F_OK) <<endl; if(0!=access(fpath.c_str(), F_OK)){ fclose(fd); fd = NULL; cout << "file not exist" <<endl; }else{ cout << " file exist" <<endl; } if(0!=access("/dev/mmcblk0p1", F_OK)){ fclose(fd); fd = NULL; cout << "dev not exist" <<endl; } fwrite("123",3,1,fd); fflush(fd); sleep(1); } fclose(fd); cin >> ii;//执行下面一行的时候先拔掉卡 cout << "access: " << access("/mnt/tttttt.txt", F_OK) <<endl; }

三、结论

在存储过程中,拔出未close的文件,文件还会存留在系统当中。并且当挂载目录可以读写的时候才能将缓存文件刷新掉。 

最新回复(0)