D
D
Dmitry Shevchenko2021-11-22 09:45:33
C++ / C#
Dmitry Shevchenko, 2021-11-22 09:45:33

Creating a txt file and writing to it C++?

you need to create a file (if this does not exist) and write some data to it.
there are no problems with recording, but if there is no file, then there will be no recording. Tried to paste

fstream file("output.txt");
    file.open("output.txt"); file.close();

I read that the open method creates a file if there is none, but in fact nothing is created. I saw that they declare the ifstream class, but I will need this file later for writing, but it cannot be overridden, so I need to use fstream.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
res2001, 2021-11-22
@ZER0x32

See first here: https://en.cppreference.com/w/cpp/io/basic_fstream
Then here: https://en.cppreference.com/w/cpp/io/basic_filebuf/open
fstream opens the file by default (like you) in in|out mode, which means that if the file does not exist, then an error occurs (see the table at the second link). The logic is that if you open a file for reading (it doesn't matter that it also opens for writing) without additional flags, then the file must exist.
Along with ifstream, which opens a file for reading, there is also ofstream, which opens a file for writing. When using ofstream, a non-existent file will be created (see table at second link).

A
Antony, 2021-11-22
@RiseOfDeath

https://stackoverflow.com/questions/15667530/fstre... You
can read more about flags, all of a sudden, in the documentation https://www.cplusplus.com/reference/ios/ios_base/o...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question