Binary files

I'm writing a program that works with binary files, and it isn't reading the file properly:

1
2
3
4
5
6
7
8
9
10
11
typedef char byte;
...
if (!(argc-1)) return ERROR_BAD_ARGUMENTS;

// open the file
ifstream file;
file.open(args[0], ios::binary);

// get commands
byte* cmds = new byte[65535];
file.read(cmds, 65535);


cmds is not working. If I later assign it...

1
2
cmds = "[SO][EXT]H[SO][EXT]e[SO][EXT]l[SO][EXT]l[SO][EXT]o[SO][EXT],[SO][EXT] [SO][EXT]W[SO][EXT]o[SO][EXT]r[SO][EXT]l[SO][EXT]d[SO][EXT]![EXT][EXT][NUL]";
// (binary paste, i.e. [SO] == '\xE') 


...it works fine.

I assume it has to do with the control codes.
closed account (N85iE3v7)
Try this instead. Find the size of the file and then allocate your buffer. The Cplusplus.com C++ reference has a good example of how to do it. In fact I always use it.

http://www.cplusplus.com/reference/iostream/istream/read/

The code below is mix of the example and the Op source code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

int length;
typedef char byte;
...
if (!(argc-1)) return ERROR_BAD_ARGUMENTS;

  // open the file
  ifstream file;
  file.open(args[0], ios::binary);
  // get length of file:
  file.seekg (0, ios::end);
  length = file.tellg();
  file.seekg (0, ios::beg);

// get commands
byte* cmds = new byte[length];
file.read(cmds, length );
@ OP: Because this isn't exactly a "beginner" task yet you posted in the beginner forum I wanted to ask if you actually know what the code is doing here?
Thanks @zlogdan. That helped, though I realized the problem was that I should have opened args[1].

@Computergeek01 - It might be a bit advanced, but I thought my mistake was obvious and showing it to anyone else would fix it.
Topic archived. No new replies allowed.