1

I am using Visual Studio 2017 to practice C++, I have had some experience of C++ on TurboC++. Trying to create a program that reads and writes from file, I am having trouble when I use the "ios::Ate" while opening the file.

file.open("text.txt", ios::ate);

My code is as follows.

#include "pch.h"
#include <iostream>
#include <fstream>

using namespace std;

int main()
{
    fstream file;
    file.open("text.txt", ios::ate);

    char a;

    while(1){
        cin.get(a);
        if (a != '0')
            file << a;
        else break;
    }

    file.close();
}

When I run this program, is runs without errors but when I open the file it is empty.

I have tried using ios::out and it works fine but I do not want to truncate the file every time I want to write into it.

n. m. could be an AI
  • 112,515
  • 14
  • 128
  • 243

1 Answers1

1

You code assumes the file exists. you're not specifying an i/o direction, and you should always check whether an operation, e.g. file.open, succeeds.

int main()
{
    fstream file;

// open or create file if it doesn't exist, append.
    file.open("text.txt", fstream::out | fstream::app);

// did the file open?
    if (file.is_open()) {
        char a;

        while (1) {
            cin.get(a);
            if (a != '0')
                file << a;
            else break;
        }

        file.close();
    }
}
RamblinRose
  • 4,883
  • 2
  • 21
  • 33
  • I tried this, (even copied and pasted the exact code) and my file is truncated after each execution. All that is written is the most recent entry. – Pranjal Rai Mar 13 '19 at 15:47
  • Use fstream::app to append, as noted in the first comment by NathanOliver. I've amended the code accordingly. – RamblinRose Mar 13 '19 at 15:59