Writing strings and shorts as bytes

I have some data that I'm trying to write to a certain file format. I have the description of the file format, but it's in bytes (I.E. the first 4 bytes have to be a certain set of letters, the next 4 bytes is something else, etc.). I have all the data I need, but it's in the form of strings, shorts, and a short array. I was wondering how I would go about writing them to a file as bytes to make sure the format is done correctly.
You can write all three of those directly to the file using stream operators <<

The only thing I've ever had trouble with is storing doubles and floats.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include <fstream>
#include <string>
using namespace std;

int main(){

 fstream file;
 file.open("path\\file.ext",ios::out|ios::binary);

 int outInt = 12432;
 char outChar = 'f';
 string outStr = "Hello, I'm A string!";

 cout << "Outputting the following to the file \n\n"; 

 cout << outInt << " ";
 cout << outChar << " ";
 cout << outStr << " ";

 file << outInt << " ";
 file << outChar << " ";
 file << outStr << " ";

 file.close();

 cout << "\nReading the following from the file \n\n";

 file.open("path\\file.ext",ios::in|ios::binary);

 char buf = NULL;
 while(!file.eof){
  buf = file.get();
  if (!file.eof){
   cout << buf;
  }
 }
}
Just be carefull when writing short/int that the byte order is correct:big endian or little endian.

You can do this:

int i=0;
char *bytes;

bytes = (char *) &i;

then you can access byte[0] up to byte[3]. Assuming int is 4 bytes.
If you post the first few fields and the relevant data structure you have, we can make more concrete suggestions.

The general approach is, you'll most likely need to open the file in binary mode, use write to write individual fields for each record. You'll also need to use a binary editor to visually confirm that your output is correct, for the first few fields at least.
The little endian approach is what I needed. In case anyone was really curious, the file format I'm writing as is WAV.
@Duoas I love you. (not really, but you are definitely awesome)
Topic archived. No new replies allowed.