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<<"Please enter the name of the file to be modified\n";
cin>>file_name;
in_stream.open(file_name, ios::nocreate);
if(in_stream.fail())
{ cout<<"This file does not exist.\n"
<<"Would you like to create it? Enter Y or N\t";
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<<"This is version "<<version; //insert the date here also
in_stream.close();
out_stream.close();
cout<<"Your file "<<file_name<<" has been created";
}
void modify_file (char file_name[])
{ int version;
in_stream>>version;
out_stream.open(file_name);
out_stream<<"This is version "<<version++;
in_stream.close();
out_stream.close();
cout<<"Your file, "<<file_name<<", has been modified";
}
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<<"Please enter the name of the file to be modified\n";
cin>>file_name;
in_stream.open(file_name, ios::nocreate);
if(in_stream.fail())
{ cout<<"This file does not exist.\n"
<<"Would you like to create it? Enter Y or N\t";
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<<"This is version "<<version; //insert the date here also
in_stream.close();
out_stream.close();
cout<<"Your file "<<file_name<<" has been created";
}
void modify_file (char file_name[])
{ int version;
in_stream>>version;
out_stream.open(file_name);
out_stream<<"This is version "<<version++;
in_stream.close();
out_stream.close();
cout<<"Your file, "<<file_name<<", has been modified";
}