c语言文件操作流容易犯的错误

#include <stdio.h>
#include <stdlib.h>
int main()
{
    FILE *fp;
    fp=fopen("E:\\Recent Files\\test.txt","r");
    //若这里是w模式,那么 下面的代码没有进行写操作,源文件就会变成空的了
    //你输出也就没有用了,所以这里我们要注意 
    if (!fp)
    {
       printf ("can't find the files\n.");
       exit(1);//返回操作系统,关闭所有打开的文件 
       system("pause");
    }
    char ch;
    while ((ch=fgetc(fp))!=EOF)
          fputc(ch,stdout);
    
    //while ((ch=fgetc(stdin))!=EOF)
    //      fputc(ch,stdout);
    fclose(fp);
    system("pause");
    return 0;
}


正如 我们注释的地方,这个模式 我们一定要    记住不要写错了

 

#include <stdio.h>
#include <iostream>
using namespace std;
#include <stdlib.h>
int main()
{
    FILE *fp1,*fp2;
    char buffer[105];
    fp1=fopen("E:\\Recent Files\\test.txt","w");
    //fp2=fopen("E:\\Recent Files\\cherry.txt","w");
    cout<<"11111111fp1="<<fp1<<endl;
    if (NULL==fp1)
    {
       printf ("test cannt open\n");
       exit(1);           
    }
    char ch;
    while ((ch=fgetc(stdin))!='\n')
    {
          fputc(ch,fp1);
    }
    //fclose(fp1);
    cout<<"222222fp1="<<fp1<<endl;
    system("pause");
    return 0;
}


这里我们没有fclose();     所以在写这个文件时  不能成功

这里  原因我也不清楚    具体的可以看源代码吧

fopen后没fclose

那这个文件会一直被打开知道程序退出,会有一个文件描述符被一直占用直到程序退出,如果一直fopen而不fclose则会导致描述符泄漏。

 

#include <stdio.h>
#include <stdlib.h>
int main()
{
    FILE *fp1,*fp2;
    char buffer[105];
    fp1=fopen("E:\\Recent Files\\test.txt","w");
    fp2=fopen("E:\\Recent Files\\cherry.txt","w");
    if (NULL==fp1)
    {
       printf ("test cannt open\n");
       exit(1);           
    }
    if (NULL==fp2)
    {
       printf ("cherry cannt open\n");
       exit(1);           
    }
    char ch;
    while ((ch=fgetc(stdin))!='\n')
    {
          fputc(ch,fp1);
    }   
    fclose(fp1); 
    fp1=fopen("E:\\Recent Files\\test.txt","r");
    while ((ch=fgetc(fp1))!=EOF)//while (!feof(fp1))
    {
          fputc(ch,fp2);
    }
    fclose(fp2);
    fp2=fopen("E:\\Recent Files\\cherry.txt","r");
    while ((ch=fgetc(fp2))!=EOF)
    {
          fputc(ch,stdout);
    }
    fclose(fp1);
    fclose(fp2);
    system("pause");
    return 0;
}


每一次操作完  就要进行关闭文件    估计是指针的问题  

这个暂时 还没有搞清楚

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值