Hello there, I need to write a function that insert new data into a text file, and I manage to do that, but only for the first row....
When I close my program, and reopen it to key in a 2nd input, it will simplely overwrite my 1st input.
how can I insert the 2nd input at the next row of the 1st input?

here is my code:

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main()
{
    ofstream fout;
    string input;
    string title,author,category;
    float price;
      
    fout.open("library.txt");
    if (!fout.good())
    {
        cerr << "Error creating file";
	}
	 
	cout << "Title: " ;
	getline(cin, input); 
	title = input;
	
	cout << "Author: " ;
	getline(cin, input); 
	author = input;
	
	cout << "Category: ";
	getline(cin, input);
    category = input;
 
	cout << "Price: " ;
	getline(cin, input); 
	istringstream strPrice(input);
    strPrice >> price;
    
    fout<< title << '\t' << author << '\t' << category << '\t' << price << "\n";   
    fout.close();  
}

Many thanks~

Dani AI

Generated

Short answer: the file was being cleared on each open, so only the latest run's record remained. That explains 's 0-byte observation. The two approaches suggested earlier are different fixes: moving the write pointer to the end after opening only helps if the file has already survived the open, while opening the stream in append mode prevents the file from being truncated in the first place and guarantees new writes go after existing data. 's seek-to-end idea is useful in some cases; 's append-mode approach is the simplest reliable fix for simple "add a row" behavior.

Practical rules to follow: open the output stream in append mode when the intent is always to add records rather than replace the file; when a program needs to both read existing data and append new entries in one run, open for both read and write and explicitly position the pointer as needed. Always check that the stream opened successfully (is_open / stream bool), write a terminating newline for each record so entries appear on separate lines, flush/close the stream when done, and handle numeric conversions with proper validation instead of assuming success.

Troubleshooting checklist (common gotchas observed in IDEs and on different platforms): confirm the working directory and exact filename (case-sensitive on some systems), rule out a path typo that creates a different empty file, verify file permissions and that no other process is truncating or replacing the file, and test with a minimal write–close–reopen cycle to isolate the problem. For production code, use RAII (scoped stream objects) plus clear error handling so an accidental truncation or failed open is detected and handled instead of silently losing data.

Recommended Answers

All 6 Replies

A couple ways to solve your problem:

1. after opening the file call seekp(ios::end); set the file pointer to end-of-file before writing

2. Add the ios::ate flag to the open statement: fout.open("library.txt", ios::out | ios::ate);

Hi, Ancient Dragon, I tried both of your codes, but it still replace the 1st row's data, is it my codes got problems?

how i follow your code is like:

fout.open("library.txt");
fout.seekp(ios::end);
if (!fout.good())
.
.
.

2nd one:

fout.open("library.txt", ios::out | ios::ate);
    if (!fout.good())
.
.
.

thanks~

try this:

fout.open("library.txt");
if( fout.is_open())
{
    fout.seekp(0,ios_base::end);
    // blabla
}

If that doesn't work then post how fout was declared.

i found the problem, when everytime i reopen the program, my library.txt will be empty(0 byte), that is why it will only display the last inputs.

is it

fout.open("library.txt");

create a new "library.txt", but not open "library.txt"?

try
fout.open("Library.txt", ios::app);
i use it n it works....

try
fout.open("Library.txt", ios::app);
i use it n it works....

Thanks, it works!!!!
hahahah, thanks a lot~

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.