DevX Home    Today's Headlines   Articles Archive   Tip Bank   Forums   

Results 1 to 4 of 4

Thread: ifstream reading integer problem

  1. #1
    Join Date
    Nov 2006
    Posts
    2

    Unhappy ifstream reading integer problem

    int main()
    {
    int i1 = 1, i2 = 2;
    ofstream file("C:\\test.dat");
    file<<i1<<i2;
    file.close();

    ifstream file1("C:\\test.dat");
    file1>>i1;
    file1.close();
    cout<<i1<<endl;

    }

    the result is 12 not 1. Ints are wrote in byte by byte, but seems to be read out two bytes a time into i1 ? can anyone help me out?

  2. #2
    Join Date
    Nov 2003
    Posts
    4,118
    You need to insert a separator between the two ints, say a blank of a newline. Otherwise, when you read from the file the contiguous bytes of i1 and i2 are treated as a single long binary number.
    Danny Kalev

  3. #3
    Join Date
    May 2006
    Posts
    176
    In my opinion the "<<" and ">>" operators are for writting and reading integers in text mode. If you want to deal with binary files, I think you have to use write and read members:
    Code:
    ofstream file("C:\\test.dat", ios_base::binary);
    file.write((const char*)&i1, sizeof(i1));
    
    ifstream file1("C:\\test.dat", ios_base::binary);
    file1.read((char*)&i1, sizeof(i1));
    I hope this helps.

  4. #4
    Join Date
    Nov 2006
    Posts
    2

    Wink problem solved

    first, 3x all.

    yes, >> and << are only used for text file. bcuz there isn't any parameter to indicate the num of bytes you want to read or write, there must be some seperator to identify the end of an object. It's unnecessary for binary file bcuz WRITE and READ both have such a parameter!

Similar Threads

  1. Problem with reading chinese file..!!
    By kcpravin in forum Java
    Replies: 1
    Last Post: 06-28-2006, 05:47 AM
  2. Replies: 3
    Last Post: 04-08-2006, 06:38 PM
  3. Problem using EnumDisplaySettings
    By MulaChula in forum VB Classic
    Replies: 7
    Last Post: 04-24-2005, 02:00 AM
  4. PrintDlgEx woes
    By IvanP in forum VB Classic
    Replies: 14
    Last Post: 04-18-2002, 10:45 PM
  5. Problem: Reading text file with comma
    By Paolo in forum VB Classic
    Replies: 3
    Last Post: 01-08-2001, 09:59 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center
 
 
FAQ
Latest Articles
Java
.NET
XML
Database
Enterprise
Questions? Contact us.
C++
Web Development
Wireless
Latest Tips
Open Source


   Development Centers

   -- Android Development Center
   -- Cloud Development Project Center
   -- HTML5 Development Center
   -- Windows Mobile Development Center