Skip to content

Latest commit

 

History

History
129 lines (104 loc) · 4.15 KB

52.文件操作函数.md

File metadata and controls

129 lines (104 loc) · 4.15 KB

其它文件操作函数

  • ftell 函数
函数声明long ftell ( FILE * stream );
所在文件stdio.h
函数功能得到流式文件的当前读写位置,其返回值是当前读写位置偏离文件头部的字节数.
参数及返回解析
参数FILE * 流文件句柄
返回值int 成功,返回当前读写位置偏离文件头部的字节数。失败, 返回-1
#include<stdio.h>intmain() { char*str="123456789"; FILE*fp=fopen("test.txt", "w+"); longcp=ftell(fp); printf("cp = %li\n", cp); // 0// 写入一个字节fputc(str[0], fp); cp=ftell(fp); printf("cp = %li\n", cp); // 1fclose(fp); return0; }
  • rewind 函数
函数声明void rewind ( FILE * stream );
所在文件stdio.h
函数功能 将文件指针重新指向一个流的开头。
参数及返回解析
参数FILE * 流文件句柄
返回值void 无返回值
#include<stdio.h>intmain() { char*str="123456789"; FILE*fp=fopen("test.txt", "w+"); longcp=ftell(fp); printf("cp = %li\n", cp); // 0// 写入一个字节fputc(str[0], fp); cp=ftell(fp); printf("cp = %li\n", cp); // 1// 新指向一个流的开头rewind(fp); cp=ftell(fp); printf("cp = %li\n", cp); // 0fclose(fp); return0; }
  • fseek 函数
函数声明int fseek ( FILE * stream, long offset, int where);
所在文件stdio.h
函数功能偏移文件指针。
参数及返回解析
参 数FILE * stream 文件句柄
long offset 偏移量
int where 偏移起始位置
返回值int 成功返回 0 ,失败返回-1
  • 常用宏
#defineSEEK_CUR 1 当前文字 #defineSEEK_END 2 文件结尾 #defineSEEK_SET 0 文件开头
#include<stdio.h>intmain() { FILE*fp=fopen("test.txt", "w+"); fputs("123456789", fp); // 将文件指针移动到文件结尾, 并且偏移0个单位fseek(fp, 0, SEEK_END); intlen=ftell(fp); // 计算文件长度printf("len = %i\n", len); fclose(fp); return0; }
#include<stdio.h>intmain() { FILE*fp; fp=fopen("file.txt","w+"); fputs("123456789", fp); fseek( fp, 7, SEEK_SET ); fputs("lnj", fp); fclose(fp); return0; }

捐赠支持

项目的发展离不开你的支持,如果 CNote 帮助到你打开编程的大门,请作者喝杯咖啡吧 ☕ 后续我们会继续完善更新!加油!

点击捐赠支持作者

联系我

公众号

如果大家想要实时关注我们更新的文章以及分享的干货的话,可以关注我们的微信公众号“代码情缘”。

我的公众号

close