Thread: write a file text

  1. #1
    Registered User
    Join Date
    Jul 2007
    Posts
    32

    write a file text

    hi,
    I have a file text:
    Code:
    hello
    house
    sunrise
    down
    I need change the first line to "goodnight". But how do I have to open file? in append mode it it goes at the end; out mode it'll destroyed.....
    thanks

  2. #2
    Registered User
    Join Date
    Jan 2005
    Posts
    7,366
    You have to read in the entire file, and write it back out with the lines changed that need changing. One way to do this is to read in the file, store the data in a data structure, then open the file for writing (which truncatesthe whole thing) and write out the data in the data structure. At some point you would change what you needed to change.

    Another solution is to read one item at a time and write to a temporary file. Then when you are done delete the original file and rename the temporary one.

  3. #3
    Registered Abuser Loic's Avatar
    Join Date
    Mar 2007
    Location
    Sydney
    Posts
    115
    This page may be helpful ??? Input/Output with files

  4. #4
    Registered User
    Join Date
    Jul 2007
    Posts
    32
    sorry, but my question want says without copy the file the data in a file; I just say: overwrite a file text line. Is it possible?

  5. #5
    Registered User
    Join Date
    Jan 2005
    Posts
    7,366
    Not really. If your file was binary and setup as a series of fixed lengths records, then you could do it by seeking to the place you want to modify and then writing the new, proper fixed length string. However, you are using a text file and the common way to do this with a text file is one of the two methods I mentioned above.

  6. #6
    Registered User
    Join Date
    Jul 2007
    Posts
    32
    how can I delete a file in c++?

  7. #7
    Cat without Hat CornedBee's Avatar
    Join Date
    Apr 2003
    Posts
    8,895
    With the remove() or unlink() CRT function.
    All the buzzt!
    CornedBee

    "There is not now, nor has there ever been, nor will there ever be, any programming language in which it is the least bit difficult to write bad code."
    - Flon's Law

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Formatting a text file...
    By dagorsul in forum C Programming
    Replies: 12
    Last Post: 05-02-2008, 03:53 AM
  2. Can we have vector of vector?
    By ketu1 in forum C++ Programming
    Replies: 24
    Last Post: 01-03-2008, 05:02 AM
  3. Basic text file encoder
    By Abda92 in forum C Programming
    Replies: 15
    Last Post: 05-22-2007, 01:19 PM
  4. How to write data in exist text file?
    By ooosawaddee3 in forum C++ Programming
    Replies: 2
    Last Post: 10-20-2002, 05:55 AM