0

I have used std::fstream for reading and writing from a file, but it appeared, that after writing i couldn't do reading right away, the console would crash. I tried closing the file after writing and reopening before reading, and got no crashes, so is that the real issue here? Here are the codes for both cases

Without closing:

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

With closing/reopening:

#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;
}
Julian Go
  • 4,442
  • 3
  • 23
  • 28
J.Doe
  • 1
  • 2
  • 3
    possible duplicate of [Reading and writing to the same file using the same fstream](http://stackoverflow.com/questions/17536570/reading-and-writing-to-the-same-file-using-the-same-fstream) – Julian Go Aug 17 '15 at 15:58

1 Answers1

3

When you read/write from a file, there is a "cursor" which stores the actual position in the file. After you write, this cursor is set to the end of what you wrote. So in order to read the data you just wrote you have to reset the cursor to the beginning of the file, or to whatever position you want to read. Try this code:

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;
}
Seba Arriagada
  • 381
  • 1
  • 12