简体   繁体   English

无法在 C++ 中使用相同的 fstream 对象进行读写

[英]unable to read and write using same fstream object in c++

I'm trying to use same fstream object for first write the file and after that read the file.我正在尝试使用相同的 fstream 对象先写入文件,然后再读取文件。 when I'm using below code then the codes of writing the file is working but I'm getting junk output instead of texts which written in the file.当我使用下面的代码时,编写文件的代码正在运行,但我得到的是垃圾输出而不是文件中写入的文本。

#include<iostream>
#include<fstream>
#include<string>
using namespace std;

int main() {
    fstream file;
    file.open("test.txt",ios::in|ios::out| ios::trunc);

    if (!file) {
        cout << "Error";
    }
    else {
        cout << "success";
        file <<"\n\n1st Line\n 2nd line \n 3rd line\n";
        string filecontent;
        while (file.good()) {
            getline(file, filecontent);
            cout << filecontent << endl;
        }
    }
    return 0;
}

Output输出

This code has two separate problems.这段代码有两个不同的问题。 The first (which others have already pointed out to at least some degree) is that your loop isn't detecting the end of the file correctly.第一个(其他人至少在某种程度上已经指出)是您的循环没有正确检测到文件的结尾。 In fact, almost any time you use while (!file.eof()) or while (file.good()) , it's going to be a mistake--it won't detect end of file at the right time, so (for example) when you reach the end of the file, you won't detect it at the right time, and you'll see the last item in the file appear to be read twice before the loop exits.事实上,几乎任何时候你使用while (!file.eof())while (file.good()) ,这都将是一个错误——它不会在正确的时间检测到文件结尾,所以(例如)当您到达文件末尾时,您不会在正确的时间检测到它,并且您会看到文件中的最后一项在循环退出之前似乎被读取了两次。

In addition to that, however, you have a problem in that you're writing to the file, then immediately trying to read.然而,除此之外,您还有一个问题,即您正在写入文件,然后立即尝试读取。 That's simply not allowed--you want to do a seek any time you switch between reading and writing.这根本是不允许的——你想在阅读和写作之间切换时进行一次搜索。

In this case, you have a bit of a further problem.在这种情况下,您还有一个更进一步的问题。 Since you've just written data into the file, your file's current position is at the end of the file.由于您刚刚将数据写入文件,因此文件的当前位置位于文件末尾。 So even if you could just start reading without seeking, you'd start reading from the end of the file.因此,即使您可以不查找而直接开始阅读,您也会从文件末尾开始阅读。 That, of course, would immediately fail.当然,这会立即失败。

So you also really need to seek back to the beginning of the file to be able to read it back in.所以你真的需要回到文件的开头才能读回它。

So, the big changes here are adding a line like: file.seekg(0);因此,这里的重大变化是添加了如下一行: file.seekg(0); after you finish writing, but before you start to try to read that data back in, and then changing your reading loop to something like:在您完成写入之后,但在您开始尝试重新读取该数据之前,然后将您的读取循环更改为以下内容:

    while (getline(file, filecontent)) {
        cout << filecontent << endl;
    }

One last point: although it's not going to make a big difference in this case, I'd advise using "\\n" instead of std::endl .最后一点:虽然在这种情况下不会有太大的不同,但我建议使用"\\n"而不是std::endl std::endl writes a new-line and flushes the file buffer. std::endl写入一个新行刷新文件缓冲区。 When you're writing to the screen it won't make any real difference, but when writing to a normal file flushing the buffer unnecessarily can and will slow your code substantially (10x slower is pretty common).当您写入屏幕时,它不会产生任何真正的区别,但是当写入普通文件时,不必要地刷新缓冲区会大大减慢您的代码速度(慢 10 倍是很常见的)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM