一.标准IO
1.1fseek/rewind/ftell函数的详细介绍
int fseek(FILE *stream, long offset, int whence);
功能:修改光标的位置
参数:
@stream:文件指针
@offset:偏移
>0 :向后偏移
=0 :不偏移
<0 :向前偏移
@whence:
SEEK_SET, //从文件开头开始设置光标
SEEK_CUR, //从光标当前的位置开始设置
SEEK_END, //从文件结尾的位置开始设置光标
返回值:成功返回0,失败返回-1置位错误码
eg:
fseek(fp,20,SEEK_SET); //设置光标在第20个字符的位置
fseek(fp,0,SEEK_SET); //将光标定位到开头
fseek(fp,-10,SEEK_CUR);//将光标向前偏移10个字符
fseek(fp,-20,SEEK_END);//设置光标在倒数第20个字符的位置
fseek(fp,0,SEEK_END); //将光标定位到结尾
//注:对于追加方式打开的文件,定位写光标是无效的。永远都是在结尾写。
void rewind(FILE *stream);
功能:将光标的位置定位到文件的开头
参数:
@stream:文件指针
返回值:无
eg:
rewind(fp) = fseek(fp,0,SEEK_SET);
long ftell(FILE *stream);
功能:返回光标到文件开头的字符的个数
参数:
@stream:文件指针
返回值:成功返回光标的位置,失败返回-1置位错误码
1.2fseek使用的实例
#include <head.h>
typedef struct{
char name[20];
int age;
char sex;
}stu_t;
int main(int argc, const char* argv[])
{
FILE* fp;
int a = 500;
int ret;
if ((fp = fopen("./hello.txt", "w+")) == NULL)
PRINT_ERR("fopen error");
stu_t stu = {
.name = "zhangsan",
.age = 25,
.sex = 'm'
};
fwrite(&stu,1,sizeof(stu), fp);
memset(&stu,0,sizeof(stu));
printf("name = %s,age = %d,sex = %c\n",stu.name,stu.age,stu.sex);
fseek(fp,0,SEEK_SET); //将光标的位置设置到文件的开头
fread(&stu,1,sizeof(stu), fp);
printf("name = %s,age = %d,sex = %c\n",stu.name,stu.age,stu.sex);
fclose(fp);
return 0;
}
1.3ftell函数的使用
#include <head.h>
int main(int argc,const char * argv[])
{
FILE *fp;
if(argc != 2){
fprintf(stderr,"input error,try again\n");
fprintf(stderr,"usage:./a.out filename\n");
return -1;
}
if((fp = fopen(argv[1],"r")) == NULL)
PRINT_ERR("fopen error");
//将光标定位到文件的结尾,使用ftell返回文件的大小
fseek(fp,0,SEEK_END);
printf("size = %ld\n",ftell(fp));
fclose(fp);
return 0;
二.lseek函数的使用(设置光标位置)
#include <sys/types.h>
#include <unistd.h>
off_t lseek(int fd, off_t offset, int whence);
功能:设置光标的位置
参数:
@fd:文件描述符
@offset:偏移
>0 向后偏移
=0 不偏移
<0 向前偏移
@whence:
SEEK_SET:从文件开头开始偏移
SEEK_CUR:从光标当前位置开始偏移
SEEK_END:从文件结尾开始偏移
返回值:成功返回光标到文件开头的偏移字节
失败返回-1置位错误码
2.1lseek函数实例
#include <head.h>
typedef struct
{
unsigned char b;
unsigned char g;
unsigned char r;
} rgb_t;
int main(int argc, const char* argv[])
{
int fd,ret;
int size, offset, width, high, bitcount=0;
if (argc != 2) {
printf("input error,try again\n");
printf("usage:./a.out filename\n");
return -1;
}
if ((fd = open(argv[1],O_RDWR)) == -1)
PRINT_ERR("fopen error");
lseek(fd, 2, SEEK_SET);
read(fd,&size,4);
printf("size = %d\n", size);
lseek(fd, 10, SEEK_SET);
read(fd,&offset,4);
printf("offset = %d\n", offset);
lseek(fd, 18, SEEK_SET);
read(fd,&width,4);
printf("width = %d\n", width);
read(fd,&high,4);
printf("high = %d\n", high);
lseek(fd, 2, SEEK_CUR);
read(fd,&bitcount,2);
printf("bitcount = %d\n", bitcount);
//548 * 1280 * 3 到548行行首的字节数
//368 * 3 第548行向后偏移368个点
//(548*1280 +368) * 3 = 2,105,424
rgb_t rgb = {0,0xff,0xff}; //黄色
lseek(fd, 54+2105424, SEEK_SET);
for(int j=0;j<62;j++){
for(int i=0;i<82;i++){
ret = write(fd,&rgb,3);
//printf("ret = %d\n",ret);
}
lseek(fd,(width-82)*3,SEEK_CUR);
}
return 0;
}