Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Modify a variable in an ofstream

Status
Not open for further replies.

rich2020

Technical User
Oct 20, 2000
6
0
0
US
I'm trying to create a text file and increment an integer variable within the file. I think the problem is that .open
truncates the file so the enter always returns 0. Is there a way to stop the file from truncating when opening the outstream?

//enter the name of file
//if file exist then update version
//if file does not exists create file
//ask if you would like to repeat
//if yes loop if no exit

#include <iostream.h>
#include <fstream.h>
#include <cstdlib>

void create_file (char file_name[]);
void modify_file (char file_name[]);
ifstream in_stream;
ofstream out_stream;


void main()
{ char file_name[16], ans;


cout<<&quot;Please enter the name of the file to be modified\n&quot;;
cin>>file_name;

in_stream.open(file_name, ios::nocreate);


if(in_stream.fail())
{ cout<<&quot;This file does not exist.\n&quot;
<<&quot;Would you like to create it? Enter Y or N\t&quot;;
cin>>ans;
if(ans == 'Y'||ans == 'y')
create_file(file_name);
else
exit(1);
}
else
modify_file(file_name);

}


void create_file (char file_name[])
{ int version = 1;

out_stream.open(file_name);
out_stream<<&quot;This is version &quot;<<version; //insert the date here also

in_stream.close();
out_stream.close();

cout<<&quot;Your file &quot;<<file_name<<&quot; has been created&quot;;
}


void modify_file (char file_name[])
{ int version;
in_stream>>version;

out_stream.open(file_name);

out_stream<<&quot;This is version &quot;<<version++;

in_stream.close();
out_stream.close();

cout<<&quot;Your file, &quot;<<file_name<<&quot;, has been modified&quot;;
}
 
you can open file in
1. write only mode - all data will be lost
2. read only mode - you will be able to change nothing in file
3. read write mode - you can read and write data at any position in the file

Ion Filipski
1c.bmp
 
The version variable still returns as 0 when I use my modify file function, even though the original file has as 1.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top