如何使用Boost库检查作为输入的字符串是否为c++中的有效目录

How to check if a string given as input is a valid directory in C++ using Boost Libraries?

本文关键字:c++ 是否 有效 字符串 输入 Boost 何使用 检查      更新时间:2023-10-16

我正在使用dev - c++ Ide进行编码,我想检查作为输入的字符串是否在c++中是一个有效的现有目录,我参考了StackOverflow上的这些帖子,但我找不到一个我能理解的解决方案-如何检查目录是否存在使用c++和winAPI在所有情况下都返回true所以没有使用)有人能帮助我解决这个问题吗?

您可能会发现这很有用:http://msdn.microsoft.com/en-us/library/bb773584%28VS.85%29.aspx

粘贴示例:

#include <windows.h>
#include <iostream.h>
#include "Shlwapi.h"
void main(void)
{
    // Valid file path name (file is there).
    char buffer_1[ ] = "C:\TEST\file.txt"; 
    char *lpStr1;
    lpStr1 = buffer_1;
    // Invalid file path name (file is not there).
    char buffer_2[ ] = "C:\TEST\file.doc"; 
    char *lpStr2;
    lpStr2 = buffer_2;
    // Return value from "PathFileExists".
    int retval;
    // Search for the presence of a file with a true result.
    retval = PathFileExists(lpStr1);
    if(retval == 1)
    {
        cout << "Search for the file path of : " << lpStr1 << endl;
        cout << "The file requested "" << lpStr1 << "" is a valid file" << endl;
        cout << "The return from function is : " << retval << endl;
    }
    else
    {
        cout << "nThe file requested " << lpStr1 << " is not a valid file" << endl;
        cout << "The return from function is : " << retval << endl;
    }
    // Search for the presence of a file with a false result.
    retval = PathFileExists(lpStr2);
    if(retval == 1)
    {
        cout << "nThe file requested " << lpStr2 << "is a valid file" << endl;
        cout << "Search for the file path of : " << lpStr2 << endl;
        cout << "The return from function is : " << retval << endl;
    }
    else
    {
        cout << "nThe file requested "" << lpStr2 << "" is not a valid file" << endl;
        cout << "The return from function is : " << retval << endl;
    }
}
OUTPUT
==============
Search for the file path of : C:TESTfile.txt
The file requested "C:TESTfile.txt" is a valid file
The return from function is : 1
The file requested "C:TESTfile.doc" is not a valid file
The return from function is : 0

使用Boost的便携式解决方案。文件系统:

#include <boost/filesystem.hpp>
//...
boost::filesystem::path dir(directory_path_string);
if (boost::filesystem::is_directory(dir) && boost::filesystem::exists(dir))
{
    // directory exists
}

尝试boost::filesystem:

#include <boost/filesystem.hpp>
if ( !boost::filesystem::exists( "my_directory" ) )
{
  std::cout << "Can't find my directory!" << std::endl;
}