fstream won't create a file
You should add fstream::out to open method like this:
file.open("test.txt",fstream::out);
More information about fstream flags, check out this link: http://www.cplusplus.com/reference/fstream/fstream/open/
std::fstream doesn't create file
You're specifying std::fstream::in
in your call to fstream::open(). This is known to force it to require an existing file.
Either remove std::fstream::in
from your mode
argument, or specify std::fstream::trunc
in addition to the other flags.
fstream not creating new file
Some pointers about fstream:
a. If you are using a back slash to specify the directory such as when using
fstream f;
f.open( "folder\file", ios::out);
it won't work, a back slash has to be preceded by a backslash, so the correct way would be:
f.open( "folder\\file", ios::out);
b. If you want to create a new file, this won't work:
f.open("file.txt", ios::in | ios::out | ios::binary);
the correct way would be to first create the file, using either ios::out or ios::trunc
f.open("file.txt". ios::out) or f.open("file.txt", ios::trunc);
and then
f.open("file.txt", ios::in | ios::out | ios::binary);
c. Finally, it could be in this order as specified in this answer,
fstream not creating file
Basically ios::in requires to already have an existing file.
Fstream fails to create new file
Best method:
void FileManager::open(std::string const& filename)
{
using std::ios_base;
if( stream_.is_open() )
stream_.close();
stream_.open( filename.c_str() ); // ...try existing file
if( !stream_.is_open() ) // ...else, create new file...
stream_.open(filename.c_str(), ios_base::in | ios_base::out | ios_base::trunc);
}
So the code tests for an existing file and, if not, creates it.
Cannot create a txt file using fstream::open
Point 1: You cannot open to read if the file doesn't exist. Fortunately you probably don't want to. Simultaneously reading and writing the same file is problematic and almost always a bad idea. Until you know you have to read and write at the same time,
- open the file for reading
- read in the file
- close the file.
- edit the file in memory
- open the file for writing
- write out the file
- close the file
If you have a really big file you can't store in memory,
- open the file for reading
- open a temporary file for writing
- read in part of the file
- edit the part you read
- write the part you read to temporary
- if more file, goto 3 (but don't use
goto
), else continue - close file
- close temporary file
- delete file
- rename temporary file to file
Point 2: You have created the txtfile folder, but have you created it in the right place? Your development environment (include of conio.h suggests Visual Studio or antique) may not be running your program from where you think it is running.
Add this to your code in main:
char buf[4097]; // really big buffer
getcwd(buf, (int)sizeof(buf)); // get working directory
std::cout << buf << std::endl; // print the working directory
If the folder printed out is not where you made the txtfile folder, you can't open the file. If you want to automatically make the folder, read here: How to make a folder/directory
Point 3: exit(1);
is a really big hammer. It is a nasty hammer. Read more here. Don't use it without a really, really good reason. In this case return
is more than enough to get you out of the function, and if you add a return value to the function, main
can test the return value to see if it should continue or return. Or you can throw an exception.
Opening a file to read and write, create it if it doesn't exist
When you open the file using fstream
:
To read, the file is required to exist;
To write you need to specify a write mode,
ofstream
would do that for you, but withfstream
you need to do it yourself:
Replaces the contents of the file when you write (ofstream
default mode).
std::fstream file("NameFile.txt", std::ios::out | std::ios::in | std::ios::trunc);
^^^^^^^^^^^^^^^
Appends to the existing data in the file when you write.
std::fstream file("NameFile.txt", std::ios::out | std::ios::in | std::ios::app);
^^^^^^^^^^^^^
Note that after reading or writing you'll need to set the offset position in the file, for instance:
std::string s = "my string";
std::string in;
file << s;
file >> in;
file >> in
will not read anything, the position indicator is at the end of the file after file << s
, you'll need to reset it if you want to read previously written data, for example:
file << s;
file.seekg(0);
file >> in;
This resets the read position indicator to the beggining of the file, before the file is read from, more about it here:
https://en.cppreference.com/w/cpp/io/basic_fstream
fstream is not creating a file in C++
Your code generally works with small changes, the file is just created in the current working directory from which your program is ran, not in the directory the executable is in. There are a lot of other things you might want to address though:
#include <iostream>
#include <fstream>
// if including things from the C standard library in a C++ program,
// use c[header] instead of [header].h; you don't need any here though.
using namespace std;
int main()
{
// no need to call open(), the constructor is overloaded
// to directly open a file so this does the same thing
ofstream file("data.dat");
if(!file)
{
cout << "Couldn't open file" << endl;
return 1;
}
file.close();
// return 0; is not needed, your program will automatically
// do this when there is no return statement
}
For detailed information on why opening the file didn't work, you could have a look at std::basic_ios::bad()
and std::basic_ios::fail()
. Checking errno
is nothing you want to do when using C++ streams for file handling.
ofstream doesn't create file in C++
try this
#include <iostream>
#include <fstream>
#ifdef _WIN32
#include <windows.h>
#define SYSERROR() GetLastError()
#else
#include <errno.h>
#define SYSERROR() errno
#endif
int main(int argc, char** argv)
{
std::ofstream of("TEXT.TXT");
if(of.is_open())
{
of<<"Some text here"<<std::endl;
of.flush();
of.close();
std::cout<<"wrote the file successfully!"<<std::endl;
}
else
{
std::cerr<<"Failed to open file : "<<SYSERROR()<<std::endl;
return -1;
}
return 0;
}
The win32 GetLastError() #define isn't tested, as I don't have a windows box handy. The errno bit works. this will at least tell you what the error is if the file open fails
How to force C++ fstream create file without append mode?
It's a little more work, but you could attempt to open the fstream
, and if it fails open (and close) an output file stream (ofstream
) which creates the file, and then try to reopen the fstream
.
Related Topics
In C++, What Is a "Namespace Alias"
How to Access the Underlying Container of Stl Container Adaptors
How to Compile Qt 5 Under Windows or Linux, 32 or 64 Bit, Static or Dynamic on Visual Studio or G++
Error When Compiling Some Simple C++ Code
How to Enable _Int128 on Visual Studio
What Range of Values Can Integer Types Store in C++
Implementing Sse 4.2's Crc32C in Software
Making Std::Vector Allocate Aligned Memory
How to Monitor a Folder with All Subfolders and Files Inside
Error , Symbol 'Vector' Could Not Be Resolved
Computing Length of a C String at Compile Time. Is This Really a Constexpr
Change Floating Point Rounding Mode