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! ๐Ÿ‘€

Replies

  • Kaustubh Katdare
    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 Sharma
    Vishal Sharma
    Actually, 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 Arulraj
    Jeffrey Arulraj
    Hey 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
    Vishal Sharma
    jeffrey samuel
    Hey 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
    oh sorry wrong code posted..
    actually its not file< its file<
  • Jeffrey Arulraj
    Jeffrey Arulraj
    yeah that be the case you have not assigned any value in the variable strtemp that is what I meant
  • grsalvi
    grsalvi
    Vishal0203
    Actually, 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
    Vishal Sharma
    grsalvi
    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.
    Wait a sec!! there is a lot of confusion over here. Let me post the exact function block of code.
    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.. ๐Ÿ˜€
  • grsalvi
    grsalvi
    find() 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()
    {
    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();
    }
    This code should have given compile time error. May be you pasted wrong code again.
    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 Sharma
    Vishal Sharma
    but 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
    grsalvi
    Vishal0203
    but 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!!
    I checked the link.Its like i said,they are using it to deal with string objects.

    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 Sharma
    Vishal Sharma
    Thanks 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??

    ex
  • Vishal Sharma
    Vishal Sharma
    I'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
    grsalvi
    Vishal0203
    Thanks 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??

    ex
    No problem buddy.Cpp is my favorite like yours.
    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<
                                        
  • grsalvi
    grsalvi
    1] 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.
  • grsalvi
    grsalvi
    2] 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 Sharma
    Vishal Sharma
    grsalvi
    2] 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 Sharma
    Vishal Sharma
    grsalvi
    1] 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
    grsalvi
    Vishal0203
    it is in .doc format as the .docx doesn't support manipulation... (bloody microsoft people)
    My 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
    grsalvi
    Vishal0203
    Are functions defined by?? I think you didn't complete the sentence...
    There are just user defined functions.
  • Vishal Sharma
    Vishal Sharma
    grsalvi
    My 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.
    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++ ๐Ÿ‘€
  • grsalvi
    grsalvi
    Vishal0203
    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++ ๐Ÿ‘€
    Yes,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.
  • Vishal Sharma
    Vishal Sharma
    grsalvi
    Yes,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.
    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. ๐Ÿ‘€
  • grsalvi
    grsalvi
    Vishal0203
    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. ๐Ÿ‘€
    Exactly,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.
  • Vishal Sharma
    Vishal Sharma
    grsalvi
    Exactly,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.
    #-Link-Snipped-#
    here is something which says that we can manipulate using visual c++
    looks a li'l complicated though!
  • grsalvi
    grsalvi
    Vishal0203
    #-Link-Snipped-#
    here is something which says that we can manipulate using visual c++
    looks a li'l complicated though!
    Exactly your situation but language used is c#.

    Edit Microsoft Word Document From Your Application - CodeProject
  • Vishal Sharma
    Vishal Sharma
    grsalvi
    Exactly your situation but language used is c#.

    Edit Microsoft Word Document From Your Application - CodeProject
    No idea about c# and java now.. that's why I'm programming in c++ ๐Ÿ˜‰
    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...