卓越飞翔博客卓越飞翔博客

卓越飞翔 - 您值得收藏的技术分享站
技术文章17188本站已运行3325

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

使用标准的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
卓越飞翔博客
上一篇: 如何在 C# 中将 IEnumerable 转换为 List 以及将 List 转换回 IEnumerable?
下一篇: 返回列表
留言与评论(共有 0 条评论)
   
验证码:
隐藏边栏