C++之判断文件是否存在的几种方法

文章目录

1. 方法一:C语言之access

可以使用C语言中unistd.h里的函数access()来判断文件是否存在,其原型如下:

int access(const char *filename, int mode);

filename是文件名,mode有下列几种方法:

mode Description
F_OK 测试文件是否存在
R_OK 测试文件是否有读权限
W_OK 测试文件是否有写权限
X_OK 测试文件是否有执行权限

返回0,表示存在,返回-1表示不存在。

  • 使用方法
#include <unistd.h>
#include <stdio.h>
 
int main(void)
{
    
    
    if (access("2.txt", F_OK) == 0)
    {
    
    
        printf("1.txt exists.\n");
    }
    else
    {
    
    
        printf("1.txt not exists.\n");
    }
    return 0;
}

2. 方法二:C++方法之ifstream

ifstream中的good方法可以判断一个文件是否存在。

#include <iostream>
#include <string>
#include <fstream>
using namespace std;

bool isFileExists_ifstream(string& name) {
    
    
    ifstream f(name.c_str());
    return f.good();
}
int main()
{
    
    
    string filename = "1.txt";

    bool ret = isFileExists_ifstream(filename);
    if (ret)
    {
    
    
        cout << "文件存在" << endl;
    }
    else
    {
    
    
        cout << "文件不存在" << endl;
    }
}

3. 方法三:fopen方法

可以使用fopen的方式尝试打开一个文件。

#include <iostream>
#include <stdio.h>
using namespace std;

bool isFileExists_fopen(string& name) {
    
    
    if (FILE *file = fopen(name.c_str(), "r")) {
    
    
        fclose(file);
        return true;
    } else {
    
    
        return false;
    }   
}

int main()
{
    
    
    string filename = "1.txt";

    bool ret = isFileExists_fopen(filename);
    if (ret)
    {
    
    
        cout << "文件存在" << endl;
    }
    else
    {
    
    
        cout << "文件不存在" << endl;
    }
}

4. 方法四:sys中的stat函数方法

sys中的stat函数可以查阅文件的状态。

#include <iostream>
#include <sys/stat.h>
using namespace std;

bool isFileExists_stat(string& name) {
    
    
  struct stat buffer;   
  return (stat(name.c_str(), &buffer) == 0); 
}

int main()
{
    
    
    string filename = "1.txt";

    bool ret = isFileExists_stat(filename);
    if (ret)
    {
    
    
        cout << "文件存在" << endl;
    }
    else
    {
    
    
        cout << "文件不存在" << endl;
    }
}

猜你喜欢

转载自blog.csdn.net/yohnyang/article/details/131342539