Hi,
I have an text file "CD details" with content as below

1~ Cast Away~ English~ Thriller~ U~
2~ Titanic~ English~ Romance~ A~
3~ Forest Gump~ English~ Life~ U~

I am trying to add some additional data to the start of each line by using a code as below

#include<iostream>
#include<fstream.h>
#include<string>
#include<istream.h>
#include<conio.h>
#include <stdio.h>
using namespace std;

class CD_data_search
{
	public:
		void find_file(int search_option,string search_string);
};
void CD_data_search::find_file(int search_option,string search_string)
{
	string s;
	char p;
	int find_count=0,find_spport=0, loop_count=0,searchVar_temp;
	long pntr_postg=0,pntr_postp=0;
	searchVar_temp = search_option;
	search_option--;//To appropriately choose the correct field.
	fstream RW_myfile("CD Details",ios::in | ios::out);
	if (RW_myfile.is_open())
	{
		while (getline(RW_myfile,s))
		{
			pntr_postg=RW_myfile.tellg();
			pntr_postp=RW_myfile.tellp();
			cout<<"pntr_post_G:"<<pntr_postg<<"\n";
			cout<<"pntr_post_P:"<<pntr_postp<<"\n";
			RW_myfile.seekp(pntr_postg, ios::beg);
			pntr_postp=RW_myfile.tellp();
			RW_myfile << "TEST";
		}//end of while loop to read the file line by line

	}//End of IF loop opening the file
	else
	{
		cout<<"error in opening file";
	}
	RW_myfile.close();
	cout<<"\n"<<"Exit Search Mode\n";
	
}//End of find_file(int , string)
int main()
{
	int a=0;
	string f;
	cout<<"enter choose ID:-\t";
	cin>>a;
	cout<<"Enter string:-\t";
	cin>>f;
	cin.get();
	CD_data_search *search_D;
	search_D= new CD_data_search;
	search_D->find_file(a,f);
	return 0;
}

But this is not working as expected, it is writing at some other position, Do any body suggest me WHY is it behaving so?

Dani AI

Generated

Short answer: inserting bytes into the middle of a text file is not supported by simple write operations — writing at a file position overwrites whatever bytes are already there. The original attempt using tellg/seekp after getline ran into two practical issues: (1) text-mode newline translation (CRLF on Windows) and stream buffering mean the logical positions returned by tellg do not necessarily map to on-disk byte offsets, and (2) switching from input to output on a single fstream requires an intervening positioning operation and care with stream state. See the C++ reference for basic_fstream and tellg/tellp for the rules and pitfalls: basic_fstream, tellg, tellp.

The simplest, robust solution (the one recommended) is to rewrite the file: read the original line-by-line, write a modified line to a temporary file, then atomically replace the original. That avoids any ambiguity about offsets or translation and works reliably across platforms:

#include <fstream>
#include <string>
#include <cstdio>

std::ifstream in("CD Details");
std::ofstream out("CD Details.tmp");
std::string line;
while (std::getline(in, line)) {
    out << "PREFIX" << line << '\n';
}
in.close();
out.close();
std::remove("CD Details");
std::rename("CD Details.tmp", "CD Details");

Notes and troubleshooting for in-place edits (only when new text length == old text length): open in binary, clear error flags before switching between reading and writing, call seekp to position the put pointer, write exactly the same number of bytes, and check fail()/bad() after writes. For true insertion (shifting subsequent data) either rewrite the file or use platform-specific memory-mapped techniques; for most use cases the temp-file rewrite is safer and easiest.

Recommended Answers

All 2 Replies

You can not simply insert stuff into existing lines of a text file. Instead, you have to completely rewrite the file. Open the original file for reading, open a new temp file for writing. In a loop, read each line of the original file and rewrite it with desired changes to the output file. After that is done, close both files, delete the original, and rename the temp to be the same name as the original.

You can not simply insert stuff into existing lines of a text file. Instead, you have to completely rewrite the file. Open the original file for reading, open a new temp file for writing. In a loop, read each line of the original file and rewrite it with desired changes to the output file. After that is done, close both files, delete the original, and rename the temp to be the same name as the original.

Are you suggesting that the above said is the exact way to edit file.
I have test this, if we can exactly point the tellp pointer to the exact location where we need to edit and then if we insert the new word then the line get edited. I had trouble while using fstream class. If I use ifstream and ofstream separately, then I am able to do it(i.e., edit the Existing file itself).

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.