C ++无法读取ofstream的路径

时间:2015-09-08 09:55:48

标签: c++ ofstream

我试图将一些行输出到程序生成的txt文件中。 如果我使用这一行

exportedList.open("test.txt");

代替以下代码段中报告的内容,它可以正常工作。 问题是我需要一个绝对路径,而不是相对于我的工作项目的路径。

通过以下内容,我获取了我的文本文件,但它是空的。

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;
}

1 个答案:

答案 0 :(得分:1)

std::ofstream和朋友无法创建目录。它们只能在现有目录中打开文件(或创建新文件)。因此,在运行程序之前必须确保路径Y:\Somepath\Otherpath存在,或者必须增强程序才能创建它。

标准C ++库目前没有创建目录的机制。由于您显然正在使用WinAPI函数,因此您也可以使用WinAPI功能进行目录创建(例如CreateDirectory)。或者使用其他库机制,例如Boost的create_directories