Home > Backend Development > C++ > How to determine if a file exists using C++?

How to determine if a file exists using C++?

WBOY
Release: 2024-06-02 22:43:00
Original
1253 people have browsed it

Methods to determine whether a file exists in C: Use the ifstream class to successfully open the file to indicate existence; use the fopen() function to return a non-null pointer to indicate existence; use the std::filesystem::exists() function to directly check the file does it exist.

How to determine if a file exists using C++?

Determining whether a file exists using C

Determining whether a file exists is a common task in programming. There are several ways to do this in C.

Method 1: Use ifstream

ifstream class is used to read files. If the file exists, the ifstream object will open successfully; otherwise, the open will fail.

#include <fstream>

int main() {
  std::ifstream file("myfile.txt");
  if (file.is_open()) {
    // 文件存在
  } else {
    // 文件不存在
  }
  file.close();
  return 0;
}
Copy after login

Method 2: Use the fopen()

fopen() function to open the file in read-only mode. If the file exists, fopen() will return a pointer to the file; otherwise, NULL will be returned.

#include <stdio.h>

int main() {
  FILE *file = fopen("myfile.txt", "r");
  if (file != NULL) {
    // 文件存在
    fclose(file);
  } else {
    // 文件不存在
  }
  return 0;
}
Copy after login

Method 3: Use std::filesystem::exists()

C 17 introduced the std::filesystem library, which contains exists() Function to check whether the file exists.

#include <iostream>
#include <filesystem>

int main() {
  std::filesystem::path path("myfile.txt");
  if (std::filesystem::exists(path)) {
    // 文件存在
  } else {
    // 文件不存在
  }
  return 0;
}
Copy after login

Practical case

Suppose you have a file named myfile.txt. To check whether it exists, you can use the following code snippet :

#include <ifstream>

int main() {
  std::ifstream file("myfile.txt");
  if (file.is_open()) {
    // 在此处处理文件存在的逻辑
    std::cout << "文件存在" << std::endl;
  } else {
    // 在此处处理文件不存在的逻辑
    std::cout << "文件不存在" << std::endl;
  }
  file.close();
  return 0;
}
Copy after login

The above is the detailed content of How to determine if a file exists using C++?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template