Search code examples
c++ofstream

C++ can't read path of ofstream


I'm trying to output some lines to a txt file generated by the program. If I use this line

exportedList.open("test.txt");

in place of the one reported in the following snippet, it works. The problem is that I need an absolute path, not a path relative to my working project.

With the following, I get my text file but is empty.

int _tmain(int argc, _TCHAR* argv[])
{
    vector<wstring> listOfFileNames;
    wofstream exportedList;
    wstring outputPath
    wstring path = L"Y:\\Somepath\\*.jpg";

    exportedList.open("Y:\\Somepath\\Otherpath\\test.txt");

    WIN32_FIND_DATA dataFile;
    HANDLE hFind;

    hFind = FindFirstFile (path.c_str(), &dataFile);


    wcout << "File is " << dataFile.cFileName << endl;
    while (FindNextFile(hFind,&dataFile)!=0){
        wcout << "File is " << dataFile.cFileName << endl;
        listOfFileNames.push_back(dataFile.cFileName);
        exportedList << dataFile.cFileName << endl;
    }
    exportedList.close();
    FindClose(hFind);
    return 0;
}

Solution

  • std::ofstream and friends are not capable of creating a directory. They can only open files (or create new ones) in existing directories. Therefore, you must make sure that the path Y:\Somepath\Otherpath exists before runnign your program, or you must enhance your program to create it.

    The standard C++ library currently has no mechanism to create a directory. Since you're apparently using WinAPI functions, you can use WinAPI functionality for directory creation as well (e.g. CreateDirectory). Or use another library mechanism, such as Boost's create_directories.