1

我正在使用带有 boost v1.52.0 的 Visual Studio 2011 C++ 刚刚添加了在子目录中搜索文件的方法,并在程序关闭时开始出现此错误:

Unhandled exception at 0x7733E3BE (ntdll.dll) in Platformer.exe: 0xC0000005: Access violation reading location 0x437FEF0C.

文件系统.h:

#ifndef FILESYSTEM_H
#define FILESYSTEM_H

#include "boost/filesystem.hpp"

namespace fs=boost::filesystem;

class FileSystem
{
public:
    static const std::string GetExePath();
    static const std::string GetFullPath(std::string fileName, std::string searchInPath = "");
};

#endif

文件系统.cpp

#include "FileSystem.h"

const std::string FileSystem::GetExePath()
{
    fs::path path = fs::current_path();
    return path.string();
}

const std::string FileSystem::GetFullPath(std::string fileName, std::string searchInPath)
{
    if(searchInPath == "") 
    {
        searchInPath = GetExePath();
    }

    fs::directory_iterator end_iter;
    for( fs::directory_iterator dir_iter(searchInPath); dir_iter!=end_iter; ++dir_iter)
    {
        if(fs::is_directory(dir_iter->status()))
        {
            return GetFullPath(fileName, dir_iter->path().string());
        }
        else if (fs::is_regular_file(dir_iter->status()))
        {
            if(dir_iter->path().filename() == fs::path(fileName).filename())
            {
                return dir_iter->path().string();
            }
        }
    }

    return std::string("");
}

我以这种方式使用它:

std::string imageFullPath = FileSystem::GetFullPath("image.png");

这段代码有什么问题?谢谢。

4

1 回答 1

0

首先,我没有提到我正在使用 SDL(简单 DirectMedia 层)库。这些库是使用#pragma comment (lib, ...) 链接的,这会导致应用程序关闭时出错。我在 Project Properties -> Linker -> Input -> Additional Dependencies 部分中定义了它们,问题就解决了。

其次 GetFullPath 方法是错误的。这是正确的:

const std::string FileSystem::GetFullPath(std::string fileName, std::string searchInPath)
{
    std::string result;

    if(searchInPath.empty()) {
        searchInPath = GetExePath();
    }

    fs::directory_iterator end_iter;
    for( fs::directory_iterator dir_iter(searchInPath); dir_iter!=end_iter; ++dir_iter)
    {
        if(fs::is_directory(dir_iter->status()))
        {
            result = GetFullPath(fileName, dir_iter->path().string());
            if(!result.empty())
            {
                break;
            }
        }
        else if (fs::is_regular_file(dir_iter->status()))
        {
            if(dir_iter->path().filename() == fs::path(fileName).filename())
            {
                result = dir_iter->path().string();
                if(!result.empty())
                {
                    break;
                }
            }
        }
    }

    return result;
}
于 2012-11-23T12:56:32.690 回答