1.标准IO
1.1fseek/ftell/rewind函数使用
1.1.1fseek/ftell/rewind函数介绍
int fseek(FILE *stream, long offset, int whence);
功能:修改光标的位置
参数:
@stream:文件指针
@offset:光标的偏移
0:不偏移
>0:向后偏移(字节)
<0:向前偏移(字节)
@whence:
SEEK_SET,//从开头开始设置光标
SEEK_CUR,//从当前位置开始设置光标
SEEK_END //从结尾开始设置光标
返回值:成功返回0,失败返回-1置位错误码
long ftell(FILE *stream);
功能:返回光标到文件开头的字节数
参数:
@stream:文件指针
返回值:成功返回光标到文件开头的字节数,失败返回-1置位错误码
void rewind(FILE *stream);
功能:将光标设置到文件的开头
参数:
@stream:文件指针
返回值:无
rewind(fp) = fseek(fp,0,SEEK_SET);
1.1.2fseek函数实例
#include <head.h>
int main(int argc,const char * argv[])
{
FILE *fp;
if((fp = fopen("./hello.txt","r+"))==NULL)
PRINT_ERR("fopen file error");
// fseek(fp,4,SEEK_SET);
fseek(fp,4,SEEK_CUR);
printf("%c\n",fgetc(fp));
// fputc('z',fp);
fseek(fp,-2,SEEK_END);
printf("%c\n",fgetc(fp));
fclose(fp);
return 0;
}
#include <head.h>
int main(int argc,const char * argv[])
{
FILE *fp;
if((fp = fopen("./hello.txt","a+"))==NULL)
PRINT_ERR("fopen file error");
//对于追加的方式打开文件,改变光标位置永远影响不了写
//写永远是在结尾的位置
// fseek(fp,4,SEEK_SET);
// fputc('V',fp);
// 对于追加的方式打开文件,可以使用fseek改变读的光标的位置
fseek(fp,4,SEEK_SET);
printf("%c\n",fgetc(fp));
fclose(fp);
return 0;
}
1.1.3ftell函数实例
请使用ftell统计文件的大小
#include <head.h>
int main(int argc, const char* argv[])
{
FILE* fp;
int size = 0;
// 1.校验用户传递的参数是否正确
if (argc != 2) {
printf("input argumemt error,try again\n");
printf("usage: ./a.out filename\n");
return -1;
}
// 2.打开文件(只读)
if ((fp = fopen(argv[1], "r")) == NULL) {
printf("fopen file error");
return -1;
}
//3.将光标设置到文件的结尾
fseek(fp,0,SEEK_END);
//4.获取文件大小
size = ftell(fp);
printf("filesize = %d\n",size);
//5.关闭文件
fclose(fp);
return 0;
}
1.1.4rewind函数实例
#include <head.h>
int main(int argc, const char* argv[])
{
FILE* fp;
int size = 0;
// 2.打开文件(只读)
if ((fp = fopen("hello.txt", "r")) == NULL) {
printf("fopen file error");
return -1;
}
//3.将光标设置到文件的结尾
fseek(fp,0,SEEK_END);
size = ftell(fp);
print