Thread: reading and writing to a file

  1. #1
    Registered User
    Join Date
    Mar 2008
    Posts
    36

    reading and writing to a file

    Hey,

    I have a file containing the number 1. I want to make a program that reads the number in the file, and then replaces the number incremented by 1.

    so far I have this, but it does not seem to work, the file remains unchanged
    Code:
    int number;
    fstream file;
    
      file.open("number.txt");
      file >> number;
      file.close();
      file.open("number.txt", ios::trunc);
      file << number+1;
      file.close();
    file:
    Code:
    1
    Cheers
    Last edited by rocketman50; 06-15-2010 at 11:55 AM.

  2. #2
    Registered User hk_mp5kpdw's Avatar
    Join Date
    Jan 2002
    Location
    Northern Virginia/Washington DC Metropolitan Area
    Posts
    3,817
    Break it down, there's not much there. To start, try testing if the file is truly open (via the is_open member function perhaps) after you attempt to open them... don't just assume that the file is open, add some debug output statements that says "yes it's open" or "no, it's not open". Next, try printing the value of number after reading it in. If that is successful, then the problem is with writing the new incremented value to the file. If it's not successful, then the read didn't work and you should work on that part.
    "Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
    -Christopher Hitchens

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