Short int - how to save to the file
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?
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;
}
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();
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;
}
精彩评论