关于C语言多指针操作文件

源代码:

#include<stdio.h>
#include<string.h>
int main(void)
{
    FILE *pf=fopen("test.txt","w");
    fputs("我是帅哥",pf);    
    FILE *pd=fopen("test.txt","r");
    char name[20];
    fgets(name,strlen("我是帅哥")*2+1,pd);
    printf("%s",name);   
    fclose(pf);
    pf=NULL;
    fclose(pd);
    pd=NULL;
    return 0;
}

输入以上代码后为什么输出的结果是这样?(原字符串是NULL)

因为数据缓冲区!!!

此时pf指针对文件的写操作,“我是帅哥”字符串会被放入缓冲区,而不是直接放入文件!!!

对此的解决方案有多种

  1. 用flush()强迫将缓冲区内的数据写回参数stream 指定的文件中。
#include<stdio.h>
#include<string.h>
int main(void)
{
    FILE *pf=fopen("test.txt","w");
    fputs("我是帅哥",pf);    
    FILE *pd=fopen("test.txt","r");
    
    fflush(pf);//解决方法
    
    char name[20];
    fgets(name,strlen("我是帅哥")*2+1,pd);
    printf("%s",name);   
    fclose(pf);
    pf=NULL;
    fclose(pd);
    pd=NULL;
    return 0;
}
  1. 关闭文件之后,缓冲区内的数据会被读入文件;所以先操作完pf写文件将其关闭再操作读文件
#include<stdio.h>
#include<string.h>
int main(void)
{
    FILE *pf=fopen("test.txt","w");
    fputs("我是帅哥",pf);    
    FILE *pd=fopen("test.txt","r");
    
    //解决方法,先关闭该文件再打开
    fclose(pf);
    pf=NULL;
    
    char name[20];
    fgets(name,strlen("我是帅哥")*2+1,pd);
    printf("%s",name);   

    fclose(pd);
    pd=NULL;
    return 0;
}
  1. rewind(),fseek()等操作文件内部位置指针也可以刷新数据缓冲区,做到fflush的效果
#include<stdio.h>
#include<string.h>
int main(void)
{
    FILE *pf=fopen("test.txt","w");
    fputs("我是帅哥",pf);    
    FILE *pd=fopen("test.txt","r");
    
    //解决方法二选一
    rewind(pf);//
    fseek(pf,0,SEEK_SET);//偏移量和起始位置任选
    //注意不推荐使用,因为这两个函数主要功能是起到指向一个所需的位置,刷新缓冲区只是附带的
     
    char name[20];
    fgets(name,strlen("我是帅哥")*2+1,pd);
    printf("%s",name);   
    fclose(pf);
    pf=NULL;
    fclose(pd);
    pd=NULL;
    return 0;
}

小编刚开始以为这个是与文件位置指针有关(刚开始认为可能是文件内部使用一个位置指针),这是错误的。

#include<stdio.h>
int main(void)
{
    FILE *pf=fopen("test.txt","r");
    FILE *pd=fopen("test.txt","r");
    //test.txt内容为abcdef
    fputc(pf);
    //ftell计算偏移量为多少的函数
    printf("%d",ftell(pf));//1
    printf("%d",ftell(pd));//0
}

从结论可以看出两个指针是各管各的。

有问题可以一起交流哦

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值