3

i made this easy code to try this fstream file ("....txt") but the file stays empty ! can someone please help ? (note that i have a "selfmade" header file that includes all the files i normally use and the namespace)

This small programm should cout everything from the File.txt and then give you the chance to type new lines to the file, to break the cin progress you use break. but like i said the file stays empty

#include <myHead.h>

int main()
{
    string line;
    int i;
    fstream myFile ("File.txt");

    if (myFile.is_open())
    {
        while (getline(myFile,line))
        {
            cout << line << "\n";
        }

        line = "0";

        for(line;line!="break";cin >> line)
    {
        if(line != "break")
            myFile << line;
    }

        myFile.close();

    }
    else
        cout << "error, File.txt cannot be opened!";

    getch();
    return 0;
}
4

2 回答 2

4

读完文件后,文件处于“到达文件末尾”的状态,这是不好的

您需要在写入(附加)之前重置流状态。这是通过流方法完成的clear()

此外,您可能希望将文件作为输入和输出显式打开: ios::in | ios::out.

于 2013-11-13T16:45:53.363 回答
0

即使它已经被回答,我想指出一个更好的结束输入的选择。如果你这样做:

#include <string>
#include <iostream>
#include <fstream>

int main(void)
{
    std::fstream file("file");
    std::string buf;

    if (file.is_open())
    {
        std::cout << "READ:" << "\n\n";
        while (getline(file, buf))
        {
            std::cout << buf << "\n";
        }

        file.clear();

        std::cout << '\n' << "WRITE:" << "\n\n";
        while (getline(std::cin, buf))
        {
            file << '\n' << buf;
            file.seekp(0, file.end);
            file.seekg(0, file.end);
        }

        file.close();
    }
    else
    {
        std::cout << "error, file could not be opened.";
    }

    return 0;
}

您可以通过按Ctrl+Z + EnterWindows 或Ctrl+DUNIX 来结束流。

于 2013-11-13T16:59:47.747 回答