Sign in to follow this  
cyberflame

ofstream delets the contents of my file

Recommended Posts

Whenever I run this it delets the contents of usernames.txt and replaces it with usrname. I want it to put usnname at the end of the file and leave the rest of the contents alone. Can anyone help?
#include <stdlib.h>
#include <iostream>			
#include <string>
#include <fstream>
//defines
#define SPACE std::cout << std::endl;
//classes and vars
std :: string usrname;
std :: string usrpass;
std :: string usrage;
std :: string usremail;
std :: string filename;
std :: string words;
//function prototypes
void input();
void createfile();
//main thingy
 using namespace std;
int main()
{

 input();
    SPACE
    system("pause");
 
 return 0;
}

void input()
{
 std::cout << "Enter the User Name you want: ";
 std::cin >> usrname;
 SPACE
 std::cout << "Enter the Password you want: ";
 std::cin >> usrpass;
 SPACE
 std::cout << "Enter your age: ";
 std::cin >> usrage;
 SPACE
 std::cout << "Enter your email adress: ";
 std::cin >> usremail;
 createfile();  
}

void createfile()
{
 ifstream fin("usernames.txt");
          while (getline(fin, words))
          {
                if (words == usrname)
                   {
                          SPACE
                          cout << "Try another user name :";
                          SPACE
                          cin >> usrname;
                          fin.seekg(0, ios::beg);
                   }
               words = " ";
          } 
 fin.close();
 filename= usrname + ".txt";
 ofstream fout("usernames.txt");
 fout.seekp(NULL, ios::end);
          fout << usrname;
     
}


Share this post


Link to post
Share on other sites
The problem lies in this line:

ofstream fout("usernames.txt");


By default, when ofstream opens a file for writing, it uses the 'out' openmode - which throws away the current contents of the file. When you come to do your seekp, it's too late - you're seeking to the end of a file that is already empty. What you want to do instead is change your openmode, probably to 'app' (for 'append'):

ofstream fout("usernames.txt", ios_base::app);

Share this post


Link to post
Share on other sites
when you open a file & write to it it overwrites whatever was in it you need to use ios::app to append to what was in it

ifstream fin("usernames.txt",ios::app);//i think it should fix it but i'm a noob so don't try many times if it doesn't work it's me who messed up

same goes for

ofstream fout("usernames.txt",ios::app);

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this