C++判斷文件是否存在

一、使用std::ifstream判斷文件是否存在

在C++中,使用std::ifstream可以方便地判斷文件是否存在。下面是一個示例代碼:

#include <iostream>
#include <fstream>
#include <string>

int main()
{
    std::string filename = "test.txt";
    std::ifstream file(filename);
    if (file.good())
    {
        std::cout << "File exists." << std::endl;
    }
    else
    {
        std::cout << "File does not exist." << std::endl;
    }
    return 0;
}

上述代碼首先使用std::ifstream打開文件,然後使用good()函數判斷文件是否存在。如果文件存在,good()函數會返回true,否則返回false

二、使用fopen函數判斷文件是否存在

除了使用std::ifstream,還可以使用C標準庫函數fopen來判斷文件是否存在。下面是一個示例代碼:

#include <stdio.h>
#include <string.h>

int main()
{
    char filename[] = "test.txt";
    FILE *file = fopen(filename, "r");
    if (file != NULL)
    {
        fclose(file);
        printf("File exists.\n");
    }
    else
    {
        printf("File does not exist.\n");
    }
    return 0;
}

上述代碼使用fopen函數打開文件,模式為”r”,如果文件存在,fopen函數會返回一個非空指針,否則返回NULL

三、使用_access函數判斷文件是否存在

Windows系統下,還可以使用_access函數來判斷文件是否存在。下面是一個示例代碼:

#include <io.h>
#include <string.h>

int main()
{
    char filename[] = "test.txt";
    if (_access(filename, 0) == 0)
    {
        printf("File exists.\n");
    }
    else
    {
        printf("File does not exist.\n");
    }
    return 0;
}

上述代碼使用_access函數來判斷文件是否存在,如果文件存在,_access函數會返回0,否則返回-1

四、使用Boost庫判斷文件是否存在

使用Boost庫也可以方便地判斷文件是否存在。下面是一個示例代碼:

#include <boost/filesystem.hpp>

int main()
{
    boost::filesystem::path filename("test.txt");
    if (boost::filesystem::exists(filename))
    {
        std::cout << "File exists." << std::endl;
    }
    else
    {
        std::cout << "File does not exist." << std::endl;
    }
    return 0;
}

上述代碼使用Boost庫中的boost::filesystem::exists函數來判斷文件是否存在。

原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/195487.html

(0)
打賞 微信掃一掃 微信掃一掃 支付寶掃一掃 支付寶掃一掃
小藍的頭像小藍
上一篇 2024-12-02 20:35
下一篇 2024-12-02 20:35

相關推薦

發表回復

登錄後才能評論