CrazyEngineers
  • Replacing word in a file using c++

    Vishal Sharma

    Vishal Sharma

    @vishal-pysGmK
    Updated: Oct 25, 2024
    Views: 1.2K
    Can anyone help me out in this..
    i've been trying it since a long time but not getting the correct approach! 👀
    0
    Replies
Howdy guest!
Dear guest, you must be logged-in to participate on CrazyEngineers. We would love to have you as a member of our community. Consider creating an account or login.
Replies
  • Kaustubh Katdare

    AdministratorNov 12, 2012

    #-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.
    Are you sure? This action cannot be undone.
    Cancel
  • Vishal Sharma

    MemberNov 12, 2012

    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<<strTemp;
    }
    
    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!
    Are you sure? This action cannot be undone.
    Cancel
  • Jeffrey Arulraj

    MemberNov 12, 2012

    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
    Are you sure? This action cannot be undone.
    Cancel
  • Vishal Sharma

    MemberNov 12, 2012

    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<<strTemp its file<<tname ( tname is the name of team which is entered by the user in the other phase of program)
    Are you sure? This action cannot be undone.
    Cancel
  • Jeffrey Arulraj

    MemberNov 12, 2012

    yeah that be the case you have not assigned any value in the variable strtemp that is what I meant
    Are you sure? This action cannot be undone.
    Cancel
  • grsalvi

    MemberNov 13, 2012

    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<<strTemp;
    }
    
    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.
    Are you sure? This action cannot be undone.
    Cancel
  • Vishal Sharma

    MemberNov 13, 2012

    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<<tname;
    }
      dept_stud();
    }
    
    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.. 😀
    Are you sure? This action cannot be undone.
    Cancel
  • grsalvi

    MemberNov 13, 2012

    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<<tname; // 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<<cat;
        }
     
        fin.close();
     
        fout.close();
     
        fileCopyStr(catFileTemp,catFile);// user defined function which copies  temp file to old file and
     
                                            // deletes temp file
      }
     
    
    Hope it helps.All the best . 👍
    Are you sure? This action cannot be undone.
    Cancel
  • Vishal Sharma

    MemberNov 13, 2012

    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!!
    Are you sure? This action cannot be undone.
    Cancel
  • grsalvi

    MemberNov 13, 2012

    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.
    Are you sure? This action cannot be undone.
    Cancel
  • Vishal Sharma

    MemberNov 14, 2012

    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<<cat;
        }
    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
    Are you sure? This action cannot be undone.
    Cancel
  • Vishal Sharma

    MemberNov 14, 2012

    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...
    Are you sure? This action cannot be undone.
    Cancel
  • grsalvi

    MemberNov 14, 2012

    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<<cat;
        }
    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<<cat;
    }
     
    /* Ans:
     
    cat.append("abc",3) : it adds 3 characters to end of string.
    For example :
     
    if cat is "123";
     
    after cat.append("xyz",3);
     
    cat becomes "123xyz".
     
    Now why "\n" was appended is some thing required by output of program.It was desired that the text file should show one category in one line(That is '\n' is between two categories).
    You may omit it ,if not required.
     
    */
    
    Are you sure? This action cannot be undone.
    Cancel
  • grsalvi

    MemberNov 14, 2012

    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 you sure? This action cannot be undone.
    Cancel
  • grsalvi

    MemberNov 14, 2012

    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 .
    Are you sure? This action cannot be undone.
    Cancel
  • Vishal Sharma

    MemberNov 14, 2012

    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)
    Are you sure? This action cannot be undone.
    Cancel
  • Vishal Sharma

    MemberNov 14, 2012

    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...
    Are you sure? This action cannot be undone.
    Cancel
  • grsalvi

    MemberNov 14, 2012

    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.
    Are you sure? This action cannot be undone.
    Cancel
  • grsalvi

    MemberNov 14, 2012

    Vishal0203
    Are functions defined by?? I think you didn't complete the sentence...
    There are just user defined functions.
    Are you sure? This action cannot be undone.
    Cancel
  • Vishal Sharma

    MemberNov 14, 2012

    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++ 👀
    Are you sure? This action cannot be undone.
    Cancel
  • grsalvi

    MemberNov 14, 2012

    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.
    Are you sure? This action cannot be undone.
    Cancel
  • Vishal Sharma

    MemberNov 14, 2012

    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. 👀
    Are you sure? This action cannot be undone.
    Cancel
  • grsalvi

    MemberNov 14, 2012

    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.
    Are you sure? This action cannot be undone.
    Cancel
  • Vishal Sharma

    MemberNov 14, 2012

    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!
    Are you sure? This action cannot be undone.
    Cancel
  • grsalvi

    MemberNov 14, 2012

    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#.

    <a href="https://www.codeproject.com/Articles/36432/Edit-Microsoft-Word-Document-From-Your-Application" target="_blank" rel="nofollow noopener noreferrer">Edit Microsoft Word Document From Your Application - CodeProject</a>
    Are you sure? This action cannot be undone.
    Cancel
  • Vishal Sharma

    MemberNov 14, 2012

    grsalvi
    Exactly your situation but language used is c#.

    <a href="https://www.codeproject.com/Articles/36432/Edit-Microsoft-Word-Document-From-Your-Application" target="_blank" rel="nofollow noopener noreferrer">Edit Microsoft Word Document From Your Application - CodeProject</a>
    No idea about c# and java now.. that's why I'm programming in c++ 😉
    I'll be learning these languages in next semester.. 😒
    Are you sure? This action cannot be undone.
    Cancel
Home Channels Search Login Register