函数fseek() 用法

函数fseek() 用法根据评论来看 应该是 fseek fp 100L 2 第三个参数 origin 设定从文件的哪里开始偏移 可能取值为 SEEK CUR SEEK END 或 SEEK SET 用法 intfseek FILE stream longoffset intfromwhere 在阅读代码时 遇到了很早之前用过的 fseek 很久没有用了 有点陌生 写出来以便下次查阅 其中 SEEK SET SEEK CUR 和 SEEK END 和依次为 0 1 和 2 fseek fp 100L 0

每天进步一点点–>函数fseek() 用法

在阅读代码时,遇到了很早之前用过的fseek(),很久没有用了,有点陌生,写出来以便下次查阅。

函数功能是把文件指针指向文件的开头,需要包含头文件stdio.h

 [cpp] view plain copy #include  
      long filesize(FILE *stream); int main(void) { 
    FILE *stream; stream = fopen("MYFILE.TXT", "w+"); fprintf(stream, "This is a test"); printf("Filesize of MYFILE.TXT is %ld bytes\n", filesize(stream)); fclose(stream); return 0; } long filesize(FILE *stream) { 
    long curpos, length; curpos = ftell(stream); fseek(stream, 0L, SEEK_END); length = ftell(stream); fseek(stream, curpos, SEEK_SET); return length; } 
[cpp] view plain copy #include  
      #define N 5  typedef struct student { 
    long sno; char name[10]; float score[3]; } STU; void fun(char *filename, STU n) { 
    FILE *fp; fp = fopen(filename, "rb+"); fseek(fp, -1L*sizeof(STU),SEEK_END); fwrite(&n, sizeof(STU), 1, fp); fclose(fp); } void main() { 
    STU t[N]={ 
    { 
   10001,"MaChao", 91, 92, 77}, { 
   10002,"CaoKai", 75, 60, 88}, { 
   10003,"LiSi", 85, 70, 78}, { 
   10004,"FangFang", 90, 82, 87}, { 
   10005,"ZhangSan", 95, 80, 88}}; STU n={ 
   10006,"ZhaoSi", 55, 70, 68}, ss[N]; int i,j; FILE *fp; fp = fopen("student.dat", "wb"); fwrite(t, sizeof(STU), N, fp); fclose(fp); fp = fopen("student.dat", "rb"); fread(ss, sizeof(STU), N, fp); fclose(fp); printf("\nThe original data :\n\n"); for (j=0; j<N; j++) { 
    printf("\nNo: %ld Name: %-8s Scores: ",ss[j].sno, ss[j].name); for (i=0; i<3; i++) [cpp] view plain copy printf("%6.2f ", ss[j].score[i]); printf("\n"); } fun("student.dat", n); printf("\nThe data after modifing :\n\n"); fp = fopen("student.dat", "rb"); fread(ss, sizeof(STU), N, fp); fclose(fp); for (j=0; j<N; j++) { 
    printf("\nNo: %ld Name: %-8s Scores: ",ss[j].sno, ss[j].name); for (i=0; i<3; i++) [cpp] view plain copy printf("%6.2f ", ss[j].score[i]); printf("\n"); } 
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/217411.html原文链接:https://javaforall.net

(0)
上一篇 2026年3月18日 上午9:37
下一篇 2026年3月18日 上午9:38


相关推荐

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号