文件
文件操作
分为两种文件:
1.文本文件
2.二进制文件
区别:
fopen()
FILE *fp;
if((fp=fopen("abc.txt","r+"))==0)
{
printf("can't find");
exit(0);
}
fclose
feof()
字符输入函数fgetc()&&fputc()
fgetc()
fputc()
字符串fgets() fputs()
fgets()
fputs()
格式化输入输出
fprintf()
fscanf()
使用示例
数据块读写和fwrite()fread()
fwrite()
fread()
struct bmp_file //BMP文件头结构
{
char type[2]; //位图文件的类型,必须为BM,我这里类型不对,所以显示有误。
unsigned int size; //位图文件的大小,以字节为单位
short rd1; // 位图文件保留字,必须为0
short rd2; // 位图文件保留字,必须为0
unsigned int offset; // 位图数据的起始位置,以相对于位图
};
struct bmp_info //图像信息区
{
unsigned int bsize; //本结构体所占用字节数,即40个字节
int width; // 位图的宽度,以像素为单位,像素数量是4字节对齐的
int height; // 位图的高度,以像素为单位
unsigned short planes; // 目标设备的级别,必须为1
unsigned short count; // 每个像素所需的位数,必须是1(双色)// 4(16色),8(256色)或24(真彩色)之一
unsigned int compression; // 位图压缩类型,必须是 0(不压缩),// 1(BI_RLE8压缩类型)或2(BI_RLE4压缩类型)之一
unsigned int sizeimage; // 位图的大小,以字节为单位
unsigned int xmeter; // 位图水平分辨率,每米像素数
unsigned int ymeter; // 位图垂直分辨率,每米像素数
unsigned int cused; // 位图实际使用的颜色表中的颜色数
unsigned int cimportant; // 位图显示过程中重要的颜色数
};
struct bmp_head {
struct bmp_file file;
struct bmp_info info;
};
struct bmp_attr {
struct bmp_head head;
int xsize, ysize,sizeimage;
int pixel_size;
int line_length;
unsigned int offset;
};
struct bmp_attr *bmp = (struct bmp_attr *)calloc(1, sizeof(struct bmp_attr));
//读取bmp的文件头
fread(bmp, sizeof(struct bmp_attr), 1, fp);
bmp->xsize = (bmp->head.info.width * 3 + 3) / 4 * 4; // 4字节补齐
bmp->ysize = bmp->head.info.height;
bmp->sizeimage = bmp->head.info.sizeimage;
bmp->offset = bmp->head.file.offset;
printf("bmp xsize = %d ysize = %d sizeimage = %d offset = %d\n",bmp->xsize,bmp->ysize,bmp->sizeimage,bmp->offset);
可以获取头文件的信息,打印出来验证。
下面关于图片数据信息的获取
for (ix = 0; ix < bmp->ysize; ++ix) {
//因为bmp文件的原点是左下角,所以bmp图片需要顺着y轴的反方向来读取
fseek(fp, bmp->head.file.offset + (bmp->ysize -1 - ix) * bmp->line_length+1, SEEK_SET); //最后一行开始读取
//读取一行像素数
fread(buf, 1, bmp->line_length, fp);