Thread: reading and writing to the same file

  1. #1
    Registered User
    Join Date
    Feb 2010
    Posts
    115

    reading and writing to the same file

    Hello

    I have 2 files

    1st file is

    1 = beer
    2 = redbull
    3 = vodka

    second file is

    [50 + 50] bottles of "1" on the wall, [50 + 50] bottles of "1".
    Take one down and pass it around, [50 + 49] bottles of "1" on the wall.
    [50 + 49] bottles of "2" on the wall, [50 + 49] bottles of "2".
    Take one down and pass it around, [50 + 48] bottles of "2" on the wall.
    [50 + 48] bottles of "1" on the wall, [50 + 48] bottles of "1".
    .....
    ....

    I want to read the numbers from the second file for example [50 + 50] and add those numbers and write to the SAME file at that place 100. I also want to change the "1" to beer.

    Can somebody direct me in the right direction. I have studied reading and writing and the different possibilities you have to do this but, I dont see how you can read and write to the same file at the same place. Also what is the best way to get the numbers out?

    Thank you in advance.

  2. #2
    Registered User
    Join Date
    Oct 2006
    Posts
    250
    A simple approach could be the following:

    * read the entire file into memory
    * modify the data in memory according to the rules you posted
    * overwrite the original file with the modified copy in memory

  3. #3
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Since you aren't dealing with fixed size records here, you cannot simply do what you are hoping. What you have to do is read everything in, modify it, and write it all back out again over top of what was there.


    Quzah.
    Hope is the first step on the road to disappointment.

  4. #4
    Registered User
    Join Date
    Feb 2010
    Posts
    115
    Owkey guys, thank you for the advice

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. reading and writing to a binary file
    By greg677 in forum C Programming
    Replies: 2
    Last Post: 05-24-2010, 08:09 PM
  2. Problems installing Mingw5.1.4
    By BlackOps in forum C Programming
    Replies: 2
    Last Post: 07-26-2009, 03:28 AM
  3. Replies: 3
    Last Post: 03-04-2005, 02:46 PM
  4. file writing and reading
    By Micko in forum C Programming
    Replies: 8
    Last Post: 01-13-2004, 11:18 AM
  5. what does this mean to you?
    By pkananen in forum C++ Programming
    Replies: 8
    Last Post: 02-04-2002, 03:58 PM