Creating a file automatically...
I'm using .NET.
Ok, here's the problem. If I don't create a file named "house.txt" before executing this program (I thought that open creates a file automatically if it doesn't already exists), it won't create the file automatically. What I'm trying to do is have the program create a file automatically if one already doesn't exist and if one already exists, simply truncate what's inside. Any ideas?
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
string file_name = "house.txt";
fstream binary_file;
binary_file.open(file_name.c_str(), ios::out | ios::trunc | ios::in | ios::binary);
if(binary_file.good())
{
cout << "The file was opened..." << endl;
}
else
{
clog << "The file was not opened..." << endl;
exit(0);
}
for(int i = 0; i < 10; i++)
{
binary_file.write((char * )( & i), sizeof(int));
}
binary_file.seekg(ios::beg);
int test = 0;
for(i = 0; i < 10; i++)
{
binary_file.read((char * )( & test), sizeof(int));
cout << test << " ";
}
binary_file.close();
cout << endl << endl;
return 0;
}
# 1 Re: Creating a file automatically...
just write (as in VC++, I don't know .NET)
if u want to open if for writing
binary_file.open(file_name.c_str(), ios::out | ios::binary);
or if u want to open if for reading
binary_file.open(file_name.c_str(), ios::in| ios::binary);
in+out together opens it for addition.
(if u only want to write, allocate ofstream and not fstream, it's enough)
# 2 Re: Creating a file automatically...
just write (as in VC++, I don't know .NET)
if u want to open if for writing
binary_file.open(file_name.c_str(), ios::out | ios::binary);
or if u want to open if for reading
binary_file.open(file_name.c_str(), ios::in| ios::binary);
in+out together opens it for addition.
(if u only want to write, allocate ofstream and not fstream, it's enough)
Addition?
I take it that it's impossible to do this with open when I have both in and out? Bummer.
# 3 Re: Creating a file automatically...
What are you talking about? Your program works fine. It creates the file if not exists. It opens and truncates it to 0 if exists.
But I don't understant why does it has the extension txt when it is a binary file. :sick:
Also, I think you should test for is_open() instead of good().
cilu at 2007-11-9 0:43:49 >

# 4 Re: Creating a file automatically...
What are you talking about? Your program works fine. It creates the file if not exists. It opens and truncates it to 0 if exists.
But I don't understant why does it has the extension txt when it is a binary file. :sick:
Also, I think you should test for is_open() instead of good().
Yeh, you're right :confused: . What the fudge was going on before :ehh: ?
# 5 Re: Creating a file automatically...
What the fudge was going on before :ehh: ?
Twilight zone, probably... Call Mulder and Scully. I have their numbers if you're interested. :D
cilu at 2007-11-9 0:45:56 >
