Im trying to write and load file to from unsigned char vector but
there seems to be problem with new line char.
code:
void fg_readfile( char *fname, vector<unsigned char> &out )
{
FILE *f;
out.clear();
unsigned char chr[2] = { 0, 0 };
int c = 0, a, s;
f = fopen(fname, "r");
fseek (f , 0 , SEEK_END);
s = ftell(f);
for( a = 0; a < s; a++ )
{
fseek (f, a, SEEK_SET); // removing this file will end somehow
// really quick
fread(chr, 1,1, f);
out.push_back(chr[0]);
}
fclose(f);
}
void fg_savefile( char *fname, const vector<unsigned char> in )
{
FILE *f;
unsigned char chr[2] = { 0, 0 };
unsigned int a;
f = fopen(fname, "w");
for( a = 0; a < in.size(); a++ )
{
// fseek (f, a, SEEK_SET);
chr[0] = in[a];
fwrite( chr, 1, 1, f);
}
fclose(f);
}
so i give a example of file ( in bytes )
113 89 45 45 10 88 123 132
after reading this and writing by using those functions inside the file will be:
113 89 45 45 13 10 88 123 132
( Ofcourse file i readed is much larger. )
Thats strange.
After some debugging i found out that fg_readfile has that bug that causes that.
A few things:
1. You should open the file in binary mode.
2. Don't read/write one character at a time, read large chunks (8 - 32k) at a time.
3. When opening the file for write, use append mode.
Thanks!
I now readed writed file like this:
f = fopen(fname, "wb"); // write
fwrite( &in[0], sizeof(unsigned char), in.size(), f);
f = fopen(fname, "rb"); // read
fread(&out[0], 1, s, f);
and it seems to work.
Some years ago i was reading files like that but something happened and i started reading one by one