Replacing word in a file using c++
Can anyone help me out in this..
i've been trying it since a long time but not getting the correct approach! ๐
i've been trying it since a long time but not getting the correct approach! ๐
Replies
-
Kaustubh Katdare#-Link-Snipped-# : Why not share the code you've attempted so that C++ experts here on CE can help you fix it? It'd be a better approach over someone writing the code from scratch.
-
Vishal SharmaActually, its a part of a big program.. Sorry for that...
I'll post the loop part... so, here it is..
string str = "(team)"; string strTemp; fstream file ("file.doc", ios::out|ios::app) while(!file.eof()) { if(strTemp == str) file<
I tried this, but the loop doesn't seem to end! there's something wrong in the conditional statement which i'm not able to figure! So I could use up some help over there! ๐ thanks! -
Jeffrey ArulrajHey am I seeing some thing wrong there is no data allocated to strtemp
Do check it out bro initially there is no data in strtemp and so the error is flagged -
Vishal Sharma
oh sorry wrong code posted..jeffrey samuelHey am I seeing some thing wrong there is no data allocated to strtemp
Do check it out bro initially there is no data in strtemp and so the error is flagged
actually its not file<its file< -
Jeffrey Arulrajyeah that be the case you have not assigned any value in the variable strtemp that is what I meant
-
grsalviVishal0203Actually, its a part of a big program.. Sorry for that...
I'll post the loop part... so, here it is..
string str = "(team)"; string strTemp; fstream file ("file.doc", ios::out|ios::app) while(!file.eof()) { if(strTemp == str) file<
I tried this, but the loop doesn't seem to end! there's something wrong in the conditional
statement which i'm not able to figure! So I could use up some help over there! ๐ thanks!
First of all the part of code pasted did not help to understand what you are actually doing.
But checkout few things :
1] " ios::app mode "
You have opened file in output mode and append mode. In this case the file output pointer is
taken directly to end of file ,when it is opened and you are not allowed to randomly edit file,that is all you can do is add new thing to file at the end.
solution : use ios::ate mode.
ios ::ate (at end ) mode also opens file with pointer end, but you are allowed to take pointer anywhere in file and do editing.
2] Are you using same file stream to read and edit file ???
solution:
If so then once the word to be edited has been read,you have to take back your pointer back to first byte of the word to be edited using file.fseekp();
One suggestion :
It is always better while editing a file,to create two file streams .One reads file and another writes a temporary file. -
Vishal Sharma
Wait a sec!! there is a lot of confusion over here. Let me post the exact function block of code.grsalviFirst of all the part of code pasted did not help to understand what you are actually doing.
But checkout few things :
1] " ios::app mode "
You have opened file in output mode and append mode. In this case the file output pointer is
taken directly to end of file ,when it is opened and you are not allowed to randomly edit file,that is all you can do is add new thing to file at the end.
solution : use ios::ate mode.
ios ::ate (at end ) mode also opens file with pointer end, but you are allowed to take pointer anywhere in file and do editing.
2] Are you using same file stream to read and edit file ???
solution:
If so then once the word to be edited has been read,you have to take back your pointer back to first byte of the word to be edited using file.fseekp();
One suggestion :
It is always better while editing a file,to create two file streams .One reads file and another writes a temporary file.
void team::team_list() { string str ="(team)";//existing word string strTemp; string tname;// to be placed in file cout<<"\n\n"<<"\t\t\t"<<"Enter the team name: "; cin.sync(); getline(cin,tname,'\n'); name +=".doc"; fstream file(tname.c_str()); CopyFile("D:\\C++\\proj\\team.doc",tname.c_str(),TRUE); file.close(); ifstream second(tname.c_str(), ios::in); while(!second.eof()) { if(strTemp == str)// I'm facing problem here second<
so here it is....... in which I'm not opening the file in append mode..... I'll brief you about what my entire program actually does. The setup consist of a main .exe file and two pre made documents documents..
the 1st document is a letter to the head of department with the necessary things which are to be entered by the user during the run-time, written as "(date)" etc. the program dynamically creates the file for each dept. and sorts the entered names according to there dept.
the 2nd document consist just a word "(team)" when the user enters the team name, the word team is replaced by the team name.. and after that the players names dept and roll numbers are appended.
So as you can see, for both the documents I have to replace a few things..
your idea about solving the problem is too complicated.. i was expecting the solution, in terms of find() and replace(). And, we do not need to seek a lot for this.. I just don't know how to use these functions!
So pleaase, if you know about these functions tell me about it because, they use less code and hence reduces the complication of seeking.
Awaiting for the best answer.. ๐ -
grsalvifind() and replace() cannot be used with files as they are member functions of string class.
Still your code seems erroneous.Please see the highlighted statements.
void team::team_list()
This code should have given compile time error. May be you pasted wrong code again.
{
string str ="(team)";//existing word
string strTemp;
string tname;// to be placed in file
cout<<"\n\n"<<"\t\t\t"<<"Enter the team name: ";
cin.sync();
getline(cin,tname,'\n');
name +=".doc";
fstream file(tname.c_str());
CopyFile("D:\\C++\\proj\\team.doc",tname.c_str(),TRUE);
file.close();
ifstream second(tname.c_str(), ios::in); / file opened for read purpose
while(!second.eof())
{
if(strTemp == str)// I'm facing problem here
second<// using second for output ???}
dept_stud();
}
But still there are more doubts like strTemp is carrying what data ?
Anyways, I am giving my own code which should work for your program .Perhaps you might feel its complicated ,but it definitely gives result and edits the text files.
And its is alternative to using fseek() function .
void Category::replace() { cout<<"Enter Category Name to be replaced in file : "; cin>>catName; string newCat; cout<<"Enter New Category : "; cin>>newCat; // new category called newCat ifstream fin; ofstream fout; fileIn(fin,catFile); // function to open file in read mode ,fin assocaited with existing file of // of categories string catFileTemp; // temp file created catFileTemp=catFile; int x=catFileTemp.find("\."); catFileTemp.insert(x,"temp"); fileOut(fout,catFileTemp); // uisng function fileOut : fout stream assocaited with temp file string cat; while(fin>>cat) // reading exiting file and writing to temp file { if(cat==catName) // when word to be replaced is detected, the new // word is inserted in temp file. { cat=newcat; } cat.append("\n",2); fout<
Hope it helps.All the best . ๐ -
Vishal Sharmabut i came across many codes around the web, in which people have used find and replace.. ๐ and the code is just about 5 - 6 lines (too less)!!
Have a look at this... this snippet is in daniweb
void rem(string &initialString, string whatToRemove){ size_t pos=initialString.find(whatToRemove); if (pos!=string::npos) initialString.erase(initialString.begin()+pos, initialString.begin()+pos+whatToRemove.length()); }
But i couldn't understand it much... That's the reason I asked the question here! ๐
#-Link-Snipped-#
Heres the link of that!! -
grsalvi
I checked the link.Its like i said,they are using it to deal with string objects.Vishal0203but i came across many codes around the web, in which people have used find and replace.. ๐ and the code is just about 5 - 6 lines (too less)!!
Have a look at this... this snippet is in daniweb
void rem(string &initialString, string whatToRemove){ size_t pos=initialString.find(whatToRemove); if (pos!=string::npos) initialString.erase(initialString.begin()+pos, initialString.begin()+pos+whatToRemove.length()); }
But i couldn't understand it much... That's the reason I asked the question here! ๐
#-Link-Snipped-#
Heres the link of that!!
initialString.find(whatToRemove) : it finds the position of first charcater of string
"whatToRemove" in string initailString.
Eg. :
string initialString="appleIsFruit";
string whatToRemove="Fruit";
size_t pos=initialString.find(whatToRemove);
action : in this case pos gets value 7 as Fruit starts at 7th location in initialString.)
initialString.erase(initialString.begin()+pos,initialString.begin()+pos+whatToRemove.length());
Instead of above statement consider a simpler one :
initailString.erase(pos,whatToRemove.length());
action :
before erase : initialString is now "appleIsFruit".
after erase : initialString is now "appleIs"; (fruit has been removed).
But,insert() ,find(),replace(), erase() and append() are associated with strings not FILES.
However to replace a word in a file requires code which is long.
If while writing files,you save objects in file then perhaps code shall decrease.
I have tried this way didn't like much. -
Vishal SharmaThanks a lot...
So I'll stick to your code here.. I do have some doubts in it!!
void Category::replace() { cout<<"Enter Category Name to be replaced in file : "; cin>>catName; string newCat; cout<<"Enter New Category : "; cin>>newCat; ifstream fin; ofstream fout; fileIn(fin,catFile); string catFileTemp; //temp file created ... (Is this a temp file created or string??) catFileTemp=catFile; int x=catFileTemp.find("\."); catFileTemp.insert(x,"temp"); fileOut(fout,catFileTemp); string cat; while(fin>>cat) { if(cat==catName) { cat=newcat; } cat.append("\n",2); // What does this line do?? fout<
I've re commented the code, check it once
remaining things are fine!!
But, I'm sorry I'm gonna use you a li'l more.. Hope you don't mind!! ๐
I have another problem over here.. dealing with the same thing though.. But i just want to know can we perform the same thing in this kind of file??
-
Vishal SharmaI'm getting a few errors in the programs you have given!
fileIn() and fileOut() functions are not in scope...
catFileTemp.insert(x,"temp");
I didn't understand this part too... -
grsalvi
No problem buddy.Cpp is my favorite like yours.Vishal0203Thanks a lot...
So I'll stick to your code here.. I do have some doubts in it!!
void Category::replace() { cout<<"Enter Category Name to be replaced in file : "; cin>>catName; string newCat; cout<<"Enter New Category : "; cin>>newCat; ifstream fin; ofstream fout; fileIn(fin,catFile); string catFileTemp; //temp file created ... (Is this a temp file created or string??) catFileTemp=catFile; int x=catFileTemp.find("\."); catFileTemp.insert(x,"temp"); fileOut(fout,catFileTemp); string cat; while(fin>>cat) { if(cat==catName) { cat=newcat; } cat.append("\n",2); // What does this line do?? fout<
I've re commented the code, check it once
remaining things are fine!!
But, I'm sorry I'm gonna use you a li'l more.. Hope you don't mind!! ๐
I have another problem over here.. dealing with the same thing though.. But i just want to know can we perform the same thing in this kind of file??
Now your query :
1] About the code
I have replaced you queries with answers in code the below.Just check out the comments.
void Category::replace() { cout<<"Enter Category Name to be replaced in file : "; cin>>catName; string newCat; cout<<"Enter New Category : "; cin>>newCat; ifstream fin; ofstream fout; fileIn(fin,catFile); string catFileTemp; [COLOR=#ff0000]//temp file created ... (Is this a temp file created or string?[/COLOR] */ans : You are correct a string is created.This string contains name of temp file. There is a function which i used below like fileIn(catFile,fin); This user defined function takes trouble to convert string catFile to char array and open file using fin.open(catFileArray,ios::in); Why did extra work of creating string then array and then file opening ?? This you very well know as strings provide more flexibility such as find() and insert() then arrays. */ catFileTemp=catFile; int x=catFileTemp.find("\."); catFileTemp.insert(x,"temp"); fileOut(fout,catFileTemp); string cat; while(fin>>cat) { if(cat==catName) { cat=newcat; } cat.append("\n",2); // What does this line do?? fout<
-
grsalvi1] fileIn() and fileOut() functions are functions defined by
2] int x=catFileTemp.find("\."); catFileTemp.insert(x,"temp");
x gets location at of '.' in string catFileTemp.
Purpose is you copies catFile to catTempFile.Now you are going to create another
file using catTempFile(that is temp).
So to add temp in file name i.e. to get file name " documentTemp.txt "
above two statements are used. -
grsalvi2] Now will it work for the certificate shown above ???
Ans :
You said that the file (having certificate details ) is already on drive .
Right ?
Can you tell in which form is it .docx or .txt . -
Vishal Sharmagrsalvi2] Now will it work for the certificate shown above ???
Ans :
You said that the file (having certificate details ) is already on drive .
Right ?
Can you tell in which form is it .docx or .txt .
it is in .doc format as the .docx doesn't support manipulation... (bloody microsoft people) -
Vishal Sharmagrsalvi1] fileIn() and fileOut() functions are functions defined by
2] int x=catFileTemp.find("\."); catFileTemp.insert(x,"temp");
x gets location at of '.' in string catFileTemp.
Purpose is you copies catFile to catTempFile.Now you are going to create another
file using catTempFile(that is temp).
So to add temp in file name i.e. to get file name " documentTemp.txt "
above two statements are used.
Are functions defined by?? I think you didn't complete the sentence... -
grsalvi
My program actually wrote,read and allowed editing in ANSI format for .txt files.Vishal0203it is in .doc format as the .docx doesn't support manipulation... (bloody microsoft people)
If the .doc is written in same format ,it will work definitely. -
grsalvi
There are just user defined functions.Vishal0203Are functions defined by?? I think you didn't complete the sentence... -
Vishal Sharma
i get problems editing this format... I surfed the web for this and found that there is a different way to manipulate this format... And it can be done only in Microsoft Visual C++ ๐grsalviMy program actually wrote,read and allowed editing in ANSI format for .txt files.
If the .doc is written in same format ,it will work definitely. -
grsalvi
Yes,even i doubt if .doc will work.Vishal0203i get problems editing this format... I surfed the web for this and found that there is a different way to manipulate this format... And it can be done only in Microsoft Visual C++ ๐
Do you think copying from .doc the content and pasting it to .txt file and then working on .txt file using your program ,will work???
Because .doc add lots of thing according to Microsoft standards which is not present in a .txt file. -
Vishal Sharma
nope.. I don't think it'll work... it'll not even seek the file.. I tried this long back.. the c++ codes cannot manipulate the borders fonts etc. ๐grsalviYes,even i doubt if .doc will work.
Do you think copying from .doc the content and pasting it to .txt file and then working on .txt file using your program ,will work???
Because .doc add lots of thing according to Microsoft standards which is not present in a .txt file. -
grsalvi
Exactly,its beyond c++ scope.C++ works on plain text format.Vishal0203nope.. I don't think it'll work... it'll not even seek the file.. I tried this long back.. the c++ codes cannot manipulate the borders fonts etc. ๐
so if you write .doc as simple text file while borders and other page designers are not omitted ,it is possible.
Find out ,what you can do and Post here ,let me know. -
Vishal Sharma
#-Link-Snipped-#grsalviExactly,its beyond c++ scope.C++ works on plain text format.
so if you write .doc as simple text file while borders and other page designers are not omitted ,it is possible.
Find out ,what you can do and Post here ,let me know.
here is something which says that we can manipulate using visual c++
looks a li'l complicated though! -
grsalvi
Exactly your situation but language used is c#.Vishal0203#-Link-Snipped-#
here is something which says that we can manipulate using visual c++
looks a li'l complicated though!
Edit Microsoft Word Document From Your Application - CodeProject -
Vishal Sharma
No idea about c# and java now.. that's why I'm programming in c++ ๐grsalviExactly your situation but language used is c#.
Edit Microsoft Word Document From Your Application - CodeProject
I'll be learning these languages in next semester.. ๐
You are reading an archived discussion.
Related Posts
Indeed there were other relevant stories associated with the History of Hacking.Here are few of them that are well known.
John Drapper also known as Captain Crunch is known as...
How can we overcome the problem 503 service unavailable in opening the website...
can anyone have its solution then kindly explain it..
Every few months, you'd hear the news that several thousand people were duped by a crook who promised to double people's investment in flat 6 months. The modus operandi of...
Love Windows? Love Internet Explorer? Don't have money and time to download the Windows 8? You will now be able to download IE 10 for Windows 7. Internet Explorer's latest...
Name : Syed Mohamed IshaqโEngg Trade : B.E. Mechatronics Engineering.โFrom : kanyakumari, TamilNadu, India.โOccupation : fresher @ TATA CONSULTANCY SERVICES LIMITED, India.โHobbies : making manual small scale robots and toysโAim...