2

I have unsigned short int (from 0 to 65535) and I must save it to the file, using stdio and consuming 2 bytes, but I don't know, how.

Any suggestions?

rhino
  • 13,543
  • 9
  • 37
  • 39
m4tx
  • 4,139
  • 5
  • 37
  • 61

3 Answers3

2

I will use an union (yeah I dislike using cast..) :

template <typename T>
union Chunk {
  T _val;
  char _data[sizeof(T)];
};

int main(void) {
   std::ofstream output;
   Chunk<short> num;
   num._val = 42;
   output.open("filepath.txt");
   if (output.good()) {
       output.write(num._data, sizeof(num));
   }
   output.close();
   return 0;
}
Errata
  • 640
  • 6
  • 10
  • 1
    You shouldn't name your members with preceding underscores. Names with preceding underscores are reserved for the compiler. See http://stackoverflow.com/questions/228783/what-are-the-rules-about-using-an-underscore-in-a-c-identifier. – Emile Cormier Feb 26 '11 at 16:52
  • 1
    @Emile: these ones aren't. Member names are not "in the global namespace". – Steve Jessop Feb 26 '11 at 16:59
1

http://www.cplusplus.com/doc/tutorial/files/ It's good to read the whole thing, but the information you need is in 'Binary files' in the bottom half of the article.

ofstream outputFile;
outputFile.open("yourfile.dat");
unsigned short int i;
i = 10;
outputFile.write(&i, sizeof(i));

outputFile.close();
GolezTrol
  • 114,394
  • 18
  • 182
  • 210
  • It doesn't work. `/mnt/Dane/Projects/Discoverer/Discoverer/src/MapClass/SaveMap.cpp|92|error: no matching function for call to ‘std::basic_fstream >::write(short unsigned int*, int)’|` – m4tx Feb 26 '11 at 15:49
  • 4
    Instead of `outputFile.write(&i, 2);` try `outputFile.write(reinterpret_cast(&i), sizeof(i));` – Emile Cormier Feb 26 '11 at 16:37
  • 1
    `sizeof(i)` or `sizeof(unsigned short)` would be preferrable to the hard-coded `2`. – Emile Cormier Feb 26 '11 at 16:46
1

If you have to use stdio.h (and not iostream):

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
  FILE* f;
  unsigned short int i = 5;
  f=fopen("yourfile","w");
  if(f == NULL)
    {
      perror("yourfile is not open");
      exit(EXIT_FAILURE);
    }
  fwrite(&i,sizeof(i),1,f);
  fclose(f);
  return 0;
}
BenjaminB
  • 1,809
  • 3
  • 18
  • 32