首页 > 文章列表 > 使用标准的C/C++,检查文件是否存在的最佳方法是什么?

使用标准的C/C++,检查文件是否存在的最佳方法是什么?

文件存在检查的关键词: 文件存在检查 标准C 文件检查方法
393 2023-09-17

检查文件是否存在的唯一方法是尝试以读取或写入的方式打开文件。

下面是一个示例:

在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