【问题标题】:Do i need to close a file after writing and before reading?我需要在写入之后和读取之前关闭文件吗?
【发布时间】:2015-08-10 14:29:14
【问题描述】:

我使用std::fstream 来读取和写入文件,但似乎写入后我无法立即读取,控制台会崩溃。我尝试在写入后关闭文件并在读取前重新打开,并且没有崩溃,所以这是真正的问题吗?这是两种情况的代码

不关闭:

#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <stdlib.h>



int _tmain(int argc, _TCHAR* argv[])
{
    std::fstream output("text.txt", std::ios::out | std::ios::in | std::ios::trunc);
    if (!output)
    {
        std::cerr << "Error";
        exit(1);
    }
    char a[10], b[10];
    std::cin >> b;
    output << b;
    output >> a;
    std::cout << a;
    return 0;
}

关闭/重新打开:

#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <stdlib.h>



int _tmain(int argc, _TCHAR* argv[])
{
    std::fstream output("text.txt", std::ios::out | std::ios::in | std::ios::trunc);
    if (!output)
    {
        std::cerr << "Error";
        exit(1);
    }
    char a[10], b[10];
    std::cin >> b;
    output << b;
    output.close();
    output.open("text.txt");
    output >> a;
    std::cout << a;
    return 0;
}

【问题讨论】:

标签: c++ fstream


【解决方案1】:

当您从文件读取/写入时,会有一个“光标”存储文件中的实际位置。写入后,此光标将设置到您所写内容的末尾。因此,为了读取您刚刚写入的数据,您必须将光标重置到文件的开头,或者您想要读取的任何位置。 试试这个代码:

int _tmain(int argc, _TCHAR* argv[])
{
    std::fstream output("text.txt", std::ios::out | std::ios::in | std::ios::trunc);
    if (!output)
    {
        std::cerr << "Error";
        exit(1);
    }
    char a[10], b[10];
    std::cin >> b;
    output << b;
    output.seekp(std::ios_base::beg); // reset to the begin of the file
    output >> a;
    std::cout << a;
    return 0;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-04-20
    • 2017-03-21
    • 1970-01-01
    • 2020-10-24
    • 1970-01-01
    • 1970-01-01
    • 2023-03-29
    • 2020-12-18
    相关资源
    最近更新 更多