C-Programmierung
Binärdaten
← Textdaten | ● | Standard Datei Deskriptoren →
/* write a raw file */
void writefile(const char *filename,unsigned char *data,unsigned int bytes)
{
FILE *file;
if (bytes<1)
ERRORMSG();
if ((file=fopen(filename,"wb"))==NULL)
IOERROR();
if (fwrite(data,1,bytes,file)!=bytes)
IOERROR();
fclose(file);
}
/* read a raw file */
unsigned char *readfile(const char *filename,unsigned int *bytes)
{
const unsigned int BLOCKSIZE=1<<20;
FILE *file;
unsigned char *data;
unsigned int cnt,blkcnt;
if ((file=fopen(filename,"rb"))==NULL)
return(NULL);
data=NULL;
cnt=0;
do
{
if (data==NULL)
{
if ((data=(unsigned char *)malloc(BLOCKSIZE))==NULL)
MEMERROR();
}
else
{
if ((data=(unsigned char *)realloc(data,cnt+BLOCKSIZE))==NULL)
MEMERROR();
}
blkcnt=fread(&data[cnt],1,BLOCKSIZE,file);
cnt+=blkcnt;
} while (blkcnt==BLOCKSIZE);
if (cnt==0)
{
free(data);
return(NULL);
}
if ((data=(unsigned char *)realloc(data,cnt))==NULL)
MEMERROR();
fclose(file);
*bytes=cnt;
return(data);
}
void writefile(const char *filename,unsigned char *data,unsigned int bytes)
{
FILE *file;
if (bytes<1)
ERRORMSG();
if ((file=fopen(filename,"wb"))==NULL)
IOERROR();
if (fwrite(data,1,bytes,file)!=bytes)
IOERROR();
fclose(file);
}
/* read a raw file */
unsigned char *readfile(const char *filename,unsigned int *bytes)
{
const unsigned int BLOCKSIZE=1<<20;
FILE *file;
unsigned char *data;
unsigned int cnt,blkcnt;
if ((file=fopen(filename,"rb"))==NULL)
return(NULL);
data=NULL;
cnt=0;
do
{
if (data==NULL)
{
if ((data=(unsigned char *)malloc(BLOCKSIZE))==NULL)
MEMERROR();
}
else
{
if ((data=(unsigned char *)realloc(data,cnt+BLOCKSIZE))==NULL)
MEMERROR();
}
blkcnt=fread(&data[cnt],1,BLOCKSIZE,file);
cnt+=blkcnt;
} while (blkcnt==BLOCKSIZE);
if (cnt==0)
{
free(data);
return(NULL);
}
if ((data=(unsigned char *)realloc(data,cnt))==NULL)
MEMERROR();
fclose(file);
*bytes=cnt;
return(data);
}
siehe auch http://code.google.com/p/libmini/source/browse/libmini/mini/miniio.cpp
← Textdaten | ● | Standard Datei Deskriptoren →