0

I am trying to write song information to a text file but nothing is being written to it. The part where I am trying to write the information to onF is running but the file is blank. BTW the code below is part of a recursive function which is the reason for the first few if statements. Any ideas?

void writeToFile(int artist, int album, int song, int nA, int nAl, int nS)
{    
    ofstream onF("library.txt");
    if(song>=nS)
    {
        album+=1;
        song = 0;
    }
    if(album>=nAl)
    {
        artist++;
        album = 0;
        song = 0;
    }
    if(artist>=nA)
    {
        onF.close();
        return;
    }
    if(onF.is_open())
    {
         onF<<artists[artist].artistName<<'#';
         onF<<artists[artist].albums[album].albumName<<'#';
         onF<<artists[artist].albums[album].songs[song].songName<<'#';
         onF<<artists[artist].albums[album].songs[song].songLength<<endl;
         cout<<"RAN"<<endl;
    }
    else
        cout<<"File could not be opened."<<endl;
    song++;
    int numAlbums = artists[artist].numAlbums;
    int numSongs = artists[artist].albums[album].numSongs;
    writeToFile(artist, album, song, nA, numAlbums, numSongs);
 }

Now that I have that working I am having trouble loading the information from the file. It's loading the song info twice with the second time loading everything but the song title. The loop runs twice:

if(inF)
{
    while(!inF.eof())
    {
        getline(inF, newArtist, '#');
        getline(inF, newAlbum, '#');
        getline(inF, newSong, '#');
        inF>>songLength;
        cout<<"CALLED"<<endl;
        addSong(newArtist, newAlbum, newSong, songLength, numArtists, 0, 0);      
    }
    inF.close();
    if(inF.is_open())
        cout<<"FAILED TO CLOSE"<<endl;
}
user3866812
  • 3
  • 1
  • 4

1 Answers1

4

You're truncating the file on entry to the function, so the last call will erase all that has been written.

If you want to append, add the std::ios::app flag

Photon
  • 2,999
  • 1
  • 12
  • 14
  • Thanks for the help. I don't want to append though. I am trying write to the file all the information that was entered while the program was running and when the program is closed and ran again I want to load all the information back into the array. Loading the information seems to be working if I manually write in the file. Is there anything you can suggest to do? – user3866812 Dec 06 '14 at 16:53
  • I tried passing the output file in as an argument and it worked. Thanks for pointing me in the right direction! – user3866812 Dec 06 '14 at 17:02
  • Sounds like **you** need to have a `for` loop in your `write` function, so your `write` function can write the entire file. However, your code says otherwise. One option is to pass the function stream by reference to your `write` function. – Thomas Matthews Dec 06 '14 at 17:03