如何在 C++ 中使用 fstream 打开子文件夹

how to open subfolder with fstream in c++

本文关键字:fstream 文件夹 C++      更新时间:2023-10-16

你好,我想读取位于程序子文件夹中的文件。我成功地读取了程序主文件夹中的文件。但是我无法读取子文件夹中的文件。我尝试添加一个名为 subdir = "/*/" 的新字符串,并这样做来获取子文件夹,但程序拒绝使用我的字符串 subdir 采用新路径。有没有人知道如何做到这一点?我的想法快用完了,哈哈。

char resulta[ MAX_PATH];
  DWORD flicksa = GetModuleFileName(NULL,resulta,MAX_PATH);
  _chdir(std::string(resulta,GetCurrentDirectory(flicksa,resulta)).c_str());
 std::string path = "/Users/Aymann/Desktop/arraysort/2CPP-REVISIONS/Supcount/";
std::string searchPattern = "/*.cpp";
std::string fullSearchPath = path + searchPattern;
WIN32_FIND_DATA FindData;
HANDLE hFind;
hFind = FindFirstFile( fullSearchPath.c_str(), &FindData ); 
if( hFind == INVALID_HANDLE_VALUE )
{
    cout << "Error searching directoryn";
    return -1;
}
do
{
    char c;
    string filePath = path + FindData.cFileName;
    ifstream in( filePath.c_str() );
    if( in.is_open() )
    {in.get(c);
       while (in) {
         while (in && c != 'n') {
           in.get(c);
         }
         _rowcount = _rowcount + 1;
         in.get(c);
       } // do stuff with the file here
    }
    else
    {
        cout << "Problem opening file " << FindData.cFileName << "n";
    }
}
while( FindNextFile(hFind, &FindData) > 0 );
if( GetLastError() != ERROR_NO_MORE_FILES )
{
    cout << "Something went wrong during searchingn";
}

不能将通配符传递给 fstream。

解决方案:下降文件夹,打开文件。

参见 glob(), opendir(), readdir(), closedir()。