使用标准 C/C++ 检查文件是否存在最好的方式
检查文件是否存在,唯一的方法是尝试打开该文件进行读取或写入。
以下是示例 −
在 C 中
示例
#include<stdio.h>
int main() {
/* try to open file to read */
FILE *file;
if (file = fopen("a.txt", "r")) {
fclose(file);
printf("file exists");
} else {
printf("file doesn't exist");
}
}输出
file exists
在 C++ 中
示例
#include <fstream>
#include<iostream>
using namespace std;
int main() {
/* try to open file to read */
ifstream ifile;
ifile.open("b.txt");
if(ifile) {
cout<<"file exists";
} else {
cout<<"file doesn't exist";
}
}输出
file doesn't exist
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP