Thread: String manipulation

  1. #1
    Registered User
    Join Date
    May 2008
    Posts
    39

    String manipulation

    Hi


    Anyone know how i can delete just one string in a file?

    Example:

    --------------
    string1
    string2
    string3

    ENDOFFILE (EOF)
    -------------------

    I want delete the string2, what can i do to delete just this string?



    Final result

    ------------------------
    string1
    string3
    (EOF)
    -----------------------



    Thanks

  2. #2
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    Write a new file with only the strings you want to keep. (You can rename it to the old file once you're done.)

  3. #3
    Registered User
    Join Date
    Aug 2008
    Posts
    67
    You can read the file into an array, ommiting the string you want removed, and then dump it all back into the same file.

  4. #4
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Quote Originally Posted by kpreston View Post
    You can read the file into an array, ommiting the string you want removed, and then dump it all back into the same file.
    But unless you actually close and re-open the file for writing, it won't work (because a file opened as "r+" which is "read and write" will still have the last bit left in it - so in this case the last line will be duplicated). It is somewhat safer [in case the program crashes or is aborted by the user during the second half] to create a new file with a temporary name, then when the new file has been written, remove the original file, and finally rename the original to the old name.

    Of course, files can be so large that the entire file don't fit in memory, in which case the process of reading from one file and writing to the a new one is the only option.

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. C++ ini file reader problems
    By guitarist809 in forum C++ Programming
    Replies: 7
    Last Post: 09-04-2008, 06:02 AM
  2. Compile Error that i dont understand
    By bobthebullet990 in forum C++ Programming
    Replies: 5
    Last Post: 05-05-2006, 09:19 AM
  3. Replies: 4
    Last Post: 03-03-2006, 02:11 AM
  4. Linked List Help
    By CJ7Mudrover in forum C Programming
    Replies: 9
    Last Post: 03-10-2004, 10:33 PM
  5. string manipulation
    By SPEKTRUM in forum Linux Programming
    Replies: 3
    Last Post: 01-26-2002, 11:41 AM