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.
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; }
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; }
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; }
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; }
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!