fstream.open()在应该使用c ++时不会失败

时间:2018-10-25 18:52:32

标签: c++ fstream ofstream

我正在编写一段代码,该代码应该将txt文件转换为xml文件,反之亦然。

从用户那里获取现有txt文件的路径后,我将从用户那里获取创建xml文件的路径。然后,例如,我输入"blablabla"作为xml路径,并且流总是打开,而good()方法总是返回true。

无论我输入什么作为不存在的文件的路径,尽管文件没有被创建,流总是打开的。如何通过错误的路径使代码失败?

这里是我的代码:

main.cpp

switch (choice) {
    case 1 : {
        //initialize a converter
        Converter toXmlConverter = Converter();

        //set txt input path for converter
        cout << "input txt file path: " ;
        string txtPathStr;
        cin >> txtPathStr;
        const char *path = txtPathStr.c_str();

        if (!fileExistsCheck(path)) {
            cout << "file does not exist" << endl;
            break;
        }
        toXmlConverter.setNewTxtFilePath(path);


        //set xml output path for converter
        cout << "output xml file path: " ;
        string xmlPathStr;
        cin >> xmlPathStr;
        const char *xmlPath = xmlPathStr.c_str();
        toXmlConverter.setNewXmlFilePath(xmlPath);

        //perform the conversion, return true if conversion successful, false if not

        if(!toXmlConverter.convertTxtToXml()) { <-----THIS SHOULD RETURN FALSE!!!!
            cout << "bad xml output path" << endl;
        } else {
            cout << "success" << endl;
        }
        break;
    }

这是Converter类中的convertTxtToXml()方法

bool Converter::convertTxtToXml() {

    // declaring input, output files
    fstream plikTxt;
    fstream plikXml;

    plikTxt.open(newTxtFilePath, ios::in);
    plikXml.open(newXmlFilePath, ios::out);
    //checking if open/create was successful
    if (plikXml.is_open()) { <--------SHOULD RETURN FALSE WITH A BOGUS PATH
        return false;
    }

    //variable to hold currently read line
    string readLine;

    //adding xml header to plikXml
    plikXml << "<?xml version=\"1.0\"?>" << endl << "<root>" << endl;

    //looping while there are lines to read
    while (getline(plikTxt, readLine)) {

        //add <row> node for each line read
        plikXml << "<row>" << endl;

        //split read line into separate words with whitespace as a separator
        istringstream buf(readLine);
        istream_iterator<string> beg(buf), end;
        vector<string> tokens(beg, end);

        //add a column node for each of the read elements, after splitting line
        for (auto& s: tokens) {
            plikXml << "<col>" << s << "</col>" << endl;
        }

        //close the <row> node after processing line
        plikXml << "</row>" << endl;
    }
    //closing <root> node after looping through all lines
    plikXml << "</root>";

    plikTxt.close();
    plikXml.close();
    return true;
}

0 个答案:

没有答案