DaniWeb IT Discussion Community

DaniWeb IT Discussion Community (http://www.daniweb.com/forums/index.php)
-   C++ (http://www.daniweb.com/forums/forum8.html)
-   -   read & write Binary data (http://www.daniweb.com/forums/thread46334.html)

mhm_ra May 25th, 2006 1:40 pm
read & write Binary data
 
hi
i need to r write binary(hexadecimal) values into a text file then read this data and manipulate it as a number
:sad:

Dave Sinkula May 25th, 2006 1:55 pm
Re: read & write Binary data
 
Quote:

Originally Posted by mhm_ra
i need to r write binary(hexadecimal) values into a text file then read this data and manipulate it as a number

So is it binary or is it text? Do you mean that you want to write the binary text representation of a value and read this text back as its value?

mhm_ra May 25th, 2006 5:05 pm
Re: read & write Binary data
 
i write a hexadecimal value on a file using "ofstream" then i want to read this value from a file (may be as a string) and then convert it to its hexadecimal value then manipulate it(i.e add,subtract...........)
so can i do that?

Dave Sinkula May 25th, 2006 5:19 pm
Re: read & write Binary data
 
#include <iostream>
#include <fstream>

void write(const char *filename)
{
  std::ofstream file(filename);
  for ( int i = 100; i < 110; ++i )
  {
      file << std::hex << i << '\n';
  }
}

void read(const char *filename)
{
  std::ifstream file(filename);
  int value;
  while ( file >> std::hex >> value )
  {
      std::cout << "value = " << value << '\n';
  }
}

int main()
{
  static const char filename[] = "file.txt";
  write(filename);
  read(filename);
  return 0;
}

/* my output
value = 100
value = 101
value = 102
value = 103
value = 104
value = 105
value = 106
value = 107
value = 108
value = 109
*/

/* file.txt
64
65
66
67
68
69
6a
6b
6c
6d
*/


All times are GMT -4. The time now is 2:51 am.

Forum system based on vBulletin Copyright ©2000 - 2009, Jelsoft Enterprises Ltd.
©2003 - 2009 DaniWeb® LLC