Replace particular line in a file
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Page 1 of 2 12 LastLast
Results 1 to 15 of 18

Thread: Replace particular line in a file

  1. #1
    Join Date
    Nov 2011
    Location
    India
    Posts
    147

    Replace particular line in a file

    Hi,

    I want to read a file and replace a particular line in a file.

    Ex:

    temp.txt file contains below

    FilePath1: xxxxxxxxxxxxxxxxxxxxxxxxx
    FilePath2: xxxxxxxxxxxxxxxxxxxxxxxxx
    FilePath3: xxxxxxxxxxxxxxxxxxxxxxxxx
    Mode: 1

    Here My requrement is replace the 4th line Mode: 2 instead of Mode: 1.

    I was used seek method like below,

    Code:
    CStdioFile SaveFile;
    
    CString strFilePath;
    
    strFilePath =  _T("C:\\Sara\\temp.txt"); 
    
    
    if (SaveFile.Open(strFilePath, CFile::modeCreate | CFile::modeNoTruncate | CFile::modeReadWrite), &fileException)
    { 
    CString str = "MODE";
    SaveFile.ReadString(str);
    SaveFile.Seek(SaveFile.GetPosition(),CFile::begin);
    SaveFile.WriteString("MODE : 2");
    }
    The above code not working correctly.

    Pls give any idea?
    Regards,

    SaraswathiSrinath

  2. #2
    VictorN's Avatar
    VictorN is offline Super Moderator Power Poster
    Join Date
    Jan 2003
    Location
    Wallisellen (ZH), Switzerland
    Posts
    17,352

    Re: Replace particular line in a file

    Please, open the MSDN documentation about CStdioFile and its methods, read carefully about all the methods used in your code snippet...
    Then answer the following questions:
    1. Why do you assign the text to CString str if the next statement
      Code:
      SaveFile.ReadString(str);
      overwrites this text?
    2. What text (what line of your file) is read to CString str?
    3. Why do you call
      Code:
      SaveFile.Seek(SaveFile.GetPosition(),CFile::begin);
      What is the purpose of it?
    4. In what position do you write the "MODE : 2" text?
    5. Why do you use CFile::modeCreate option while it is (from MSDN):
      CFile::modeCreate
      Creates a new file if no file exists; otherwise, if the file already exists, it is attached to the CFile object and is truncated to 0 length.
    Victor Nijegorodov

  3. #3
    GCDEF is offline Elite Member Power Poster
    Join Date
    Nov 2003
    Posts
    12,067

    Re: Replace particular line in a file

    In addition to Victor's comments, you don't do anything to either position yourself on the fourth line or to ensure the line you're on contains the string you want to replace.

    Generally with text files you have to read from one file and write to another.

  4. #4
    Join Date
    Feb 2005
    Location
    Madrid (Spain)
    Posts
    511

    Re: Replace particular line in a file

    GCDEF
    In addition to Victor's comments, you don't do anything to either position yourself on the fourth line or to ensure the line you're on contains the string you want to replace.

    Generally with text files you have to read from one file and write to another.
    Code:
    CStdioFile SaveFile_read;
    CStdioFile SaveFile_write;
    
    CString strFilePath_read = _T("C:\\Sara\\temp.txt"); 
    CString strFilePath_write = _T("C:\\Sara\\temp_new.txt");
    
    BOOL bResult = 
    SaveFile_read.Open(strFilePath_read, CFile::modeRead | CFile::modeWrite) && 
    SaveFile_write.Open(strFilePath, CFile::modeCreate | CFile::modeWrite);
    
    if(bResult)
    { 
    	CString str_line;
    	while(SaveFile_read.ReadString(str_line)) {
    		if(str_line == _T("Mode: 1")) {
    			SaveFile_write.WriteString(_T("Mode: 2"));
    		} else {
    			SaveFile_write.WriteString(str_line);
    		}
    	}
    }
    
    SaveFile_read.Close();
    SaveFile_write.Close();
    Best regards.

  5. #5
    Join Date
    Nov 2011
    Location
    India
    Posts
    147

    Re: Replace particular line in a file

    Quote Originally Posted by VictorN View Post
    Please, open the MSDN documentation about CStdioFile and its methods
    I already read MSDN documentation and learned, File - create, read & write , check exist and append concepts. But a single line seek concept working. But i don't know to replace the string in a file with multiple line.

    I'm beginner sir. A simple example makes me clear easily. I already searched in MSDN.

    Just confused & wrongly used the code. sorry sir.

    Now I found, where i held after read the Mr.Juanpast's sample code.

    Thank you sir.
    Regards,

    SaraswathiSrinath

  6. #6
    Join Date
    Apr 2000
    Location
    Belgium (Europe)
    Posts
    3,824

    Re: Replace particular line in a file

    As said before... Textfiles are typically handled from start to finish and don't use direct access/positioning.

    so you don't "replace" a line in a textfile.
    you create a new file, copy everything before the line you want to change, then write your new line, then write the rest of the original file.
    you can then delete the old file and rename the new file to the old name.

    It is technically possible to do a replace, but that would typically involve accessing the file as a binary file, and doing all the reading/writing yourself rather than relying on a library. You can also only replace something with another line of equal length, there is no way to remove or insert some stuff in a text file, that would again, involve copying the file contents.

  7. #7
    Join Date
    Dec 2012
    Location
    England
    Posts
    2,308

    Re: Replace particular line in a file

    1) If that is all you want to do, why not just use a text editor to replace Mode: 1 with Mode: 2

    2) Another way of doing this without using two files under Windows is to use file mapping. This enables the contents of the file to be manipulated as memory. The sample code below is one of doing this replacing one phrase with another of the same size.

    Code:
    #include <windows.h>
    #include <cstring>
    #include <iostream>
    using namespace std;
    
    const char* fname = "temp.txt";
    const char* find = "Mode: 1";
    const char* repl = "Mode: 2";
    
    int main()
    {
    HANDLE hfile = CreateFile(fname, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
    
    	if (hfile == INVALID_HANDLE_VALUE) {
    		cout << "Cannot open file\n";
    		return 1;
    	}
    
    HANDLE hfm = CreateFileMapping(hfile, NULL, PAGE_READWRITE, 0, 0, NULL);
    
    	if (hfm == NULL) {
    		cout << "Cannot open map file\n";
    		return 2;
    	}
    
    char* pbfile = (char*)MapViewOfFile(hfm, FILE_MAP_WRITE, 0, 0, 0);
    
    	if (pbfile == NULL) {
    		cout << "Cannot map file\n";
    		return 3;
    	}
    
    char* fnd = strstr(pbfile, find);
    
    	if (fnd == NULL) {
    		cout << "String not found\n";
    		return 4;
    	}
    
    	strncpy(fnd, repl, strlen(find));
    
    	UnmapViewOfFile(pbfile);
    	CloseHandle(hfm);
    	CloseHandle(hfile);
    
    	return 0;
    }
    All advice is offered in good faith only. You are ultimately responsible for effects of your programs and the integrity of the machines they run on.

  8. #8
    Join Date
    Jun 2010
    Location
    Germany
    Posts
    2,583

    Re: Replace particular line in a file

    Another approach that requires just one disk file is opening the file for reading and read its entire contents into memory (storing it in a vector<string> for instance), then closing the file and re-opening it for wrtting, finally writing back the entire modified contents. Desired modifications can be applied during the reading or writing phase, or as a separate step in between, or any mixture of those, depending on what's most efficient for some reason or simply personal taste.

    This approach may become impractical with large files, however.
    I was thrown out of college for cheating on the metaphysics exam; I looked into the soul of the boy sitting next to me.

    This is a snakeskin jacket! And for me it's a symbol of my individuality, and my belief... in personal freedom.

  9. #9
    Join Date
    Nov 2011
    Location
    India
    Posts
    147

    Re: Replace particular line in a file

    Quote Originally Posted by juanpast View Post
    Code:
    if(bResult)
    { 
    	CString str_line;
    	while(SaveFile_read.ReadString(str_line)) {
    		if(str_line == _T("Mode: 1")) {
    			SaveFile_write.WriteString(_T("Mode: 2"));
    		} else {
    			SaveFile_write.WriteString(str_line);
    		}
    	}
    }
    I can read string line by line and also found the specified string , Enter the condition if/else but can't write the string in the file.
    How can i point the possition in the file?

    Quote Originally Posted by OReubens View Post
    You can also only replace something with another line of equal length, there is no way to remove or insert some stuff in a text file, that would again, involve copying the file contents.
    I like to replace the string with equal length only ( If string = "Mode: 1" replace "Mode: 2" and vice versa).
    Is possible with out using two files?


    Quote Originally Posted by 2kaud View Post
    Another way of doing this without using two files under Windows is to use file mapping.
    I will try this method in MFC.


    Quote Originally Posted by Eri523 View Post
    Another approach that requires just one disk file is opening the file for reading and read its entire contents into memory (storing it in a vector<string> for instance), then closing the file and re-opening it for wrtting, finally writing back the entire modified contents.
    I'm replaceing the string in a small file only. can you give any good sample.
    Regards,

    SaraswathiSrinath

  10. #10
    VictorN's Avatar
    VictorN is offline Super Moderator Power Poster
    Join Date
    Jan 2003
    Location
    Wallisellen (ZH), Switzerland
    Posts
    17,352

    Re: Replace particular line in a file

    Quote Originally Posted by saraswathisrinath View Post
    I like to replace the string with equal length only ( If string = "Mode: 1" replace "Mode: 2" and vice versa).
    Is possible with out using two files?
    Yes, and very easy. You read the whole file line by line in a buffer (in a CStringArray). Then you replace what you need in a buffer, open the same file for write/recreate and write in the whole buffer line by line.
    Victor Nijegorodov

  11. #11
    Join Date
    Nov 2011
    Location
    India
    Posts
    147

    Re: Replace particular line in a file

    Quote Originally Posted by VictorN View Post
    recreate and write in the whole buffer line by line.
    I like to replace a single string in a line, not whole buffer line by line. Is any possible?
    Regards,

    SaraswathiSrinath

  12. #12
    VictorN's Avatar
    VictorN is offline Super Moderator Power Poster
    Join Date
    Jan 2003
    Location
    Wallisellen (ZH), Switzerland
    Posts
    17,352

    Re: Replace particular line in a file

    Define "single string in a line"
    Victor Nijegorodov

  13. #13
    Join Date
    Nov 2011
    Location
    India
    Posts
    147

    Re: Replace particular line in a file

    i mean, CString str = "Mode: 1";
    Regards,

    SaraswathiSrinath

  14. #14
    VictorN's Avatar
    VictorN is offline Super Moderator Power Poster
    Join Date
    Jan 2003
    Location
    Wallisellen (ZH), Switzerland
    Posts
    17,352

    Re: Replace particular line in a file

    In your OP you wrote:
    Quote Originally Posted by saraswathisrinath View Post
    Hi,

    I want to read a file and replace a particular line in a file.

    Ex:

    temp.txt file contains below

    FilePath1: xxxxxxxxxxxxxxxxxxxxxxxxx
    FilePath2: xxxxxxxxxxxxxxxxxxxxxxxxx
    FilePath3: xxxxxxxxxxxxxxxxxxxxxxxxx
    Mode: 1

    Here My requrement is replace the 4th line Mode: 2 instead of Mode: 1.
    Did you change your requrement?


    Quote Originally Posted by saraswathisrinath View Post
    i mean, CString str = "Mode: 1";
    Well, what is the problem?
    Victor Nijegorodov

  15. #15
    Join Date
    Nov 2011
    Location
    India
    Posts
    147

    Re: Replace particular line in a file

    Quote Originally Posted by VictorN View Post
    Define "single string in a line"
    i mean, CString str = "Mode: 1"; Here str is the line data. I like to replace str instead of old data ("Mode: 2").

    Quote Originally Posted by VictorN View Post
    You read the whole file line by line in a buffer (in a CStringArray). Then you replace what you need in a buffer, open the same file for write/recreate and write in the whole buffer line by line.
    I followed the above way. Its working good. I read the full data from file and stored in CStringArray, while storing i check the particular line data & replace the line after store the CStringArray. Finally i wrote CStringArray data in the same file.

    i doesn't translate my requirement clearly . sorry for my conversation.
    Thank you for your valuable reply.
    Regards,

    SaraswathiSrinath

Page 1 of 2 12 LastLast

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  


Azure Activities Information Page

Windows Mobile Development Center


Click Here to Expand Forum to Full Width

This is a CodeGuru survey question.


Featured


HTML5 Development Center