anyone know why this wont work?

fstream f;
f.open("a.dat", ios::in | ios::out | ios::binary);

it doesnt create a.dat... also how would i switch f from read state to write state?

>it doesnt create a.dat
Are you looking in the right place?

>also how would i switch f from read state to write state?
Flush or seek, and you're good to go.

anyone know why this wont work?

fstream f;
f.open("a.dat", ios::in | ios::out | ios::binary);

it doesnt create a.dat... also how would i switch f from read state to write state?

Of course this code wouldn't create a.dat . You are asking it to open the file, not create it with those parameters.

Try the code below:

#include <iostream>
#include <fstream>

using namespace std;

int main()
{
    fstream File;
    File.open("a.dat", ios::out);      // This creates the file
    File.close();                               // Closes it
    
    //Re-open the File with the chosen stream parameters
    File.open("a.dat", ios::in | ios::out | ios::binary);
    
    if(!File.is_open())
    {
        cerr << "\n\n\tError Opening File!\n";
        cin.get();
        exit(0);
    }
    
    cout << "Hello World!\n";
    File << "Hello World!\n";
    
    char TChar;
    File.seekg(ios::beg);
    while(!File.eof())
    {
        File.get(TChar);
        cout << TChar;
    }
    
    cin.get();
    return 0;
}

You might also like to add code to check whether a.dat exists before attempting to create it again.

thanx so much :) that helped alot

thanx so much :) that helped alot

Glad it helped! :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.