ofstream delets the contents of my file

Started by
2 comments, last by cyberflame 19 years, 5 months ago
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;
     
}


[href]http://neoeden.web1000.com[/href]
Advertisement
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);

Richard "Superpig" Fine - saving pigs from untimely fates - Microsoft DirectX MVP 2006/2007/2008/2009
"Shaders are not meant to do everything. Of course you can try to use it for everything, but it's like playing football using cabbage." - MickeyMouse

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);
thanks, that worked perfectly.
[href]http://neoeden.web1000.com[/href]

This topic is closed to new replies.

Advertisement