c/c++读写文件(c方法篇)

读写文件操作

C语言方法

参考博客:函数基本介绍:

https://www.cnblogs.com/lidabo/p/6813354.html

自己写了个demo测试一下fopen、feek、fwrite、fread函数的使用,代码如下:

    void OperationFile_C() {
      FILE* fp = NULL;
      fp = fopen("D:\\test01.txt", "w");
      if (NULL == fp) {
      cout << "打开文件失败" << endl;
      }
      char ByteToWrite[20] = "\x0a\x0A\x0a\x0A";
      int num = fwrite(ByteToWrite, 1, strlen(ByteToWrite), fp);
      cout << "写入的字节数:" << num << endl;
    
      int nRet = fclose(fp);
      fp = NULL;
    
      fp = fopen("D:\\test01.txt", "r");
      if (NULL == fp) {
      cout << "打开文件失败" << endl;
      }
    
      fpos_t pos = 0;
      nRet = fseek(fp,0,SEEK_END);
      fgetpos(fp, &pos);//通过此方式可以获取出来文件的大小
      nRet = fseek(fp, 0, SEEK_SET);
      cout << "文件实际包含的字节数:" << pos << endl;
    
      char ByteToRead[40] = { 0 };
      num = fread(ByteToRead, 1, pos, fp);
      cout << "读取到的字节数:" << num << endl;
      nRet = fclose(fp);
      fp = NULL;
    
    
      fp = fopen("D:\\test01.txt", "rb");
      if (NULL == fp) {
      cout << "打开文件失败" << endl;
      }
    
      pos = 0;
      nRet = fseek(fp, 0, SEEK_END);
      fgetpos(fp, &pos);//通过此方式可以获取出来文件的大小
      nRet = fseek(fp, 0, SEEK_SET);
      cout << "文件实际包含的字节数:" << pos << endl;
    
      memset(ByteToRead, 0, sizeof(ByteToRead));
      num = fread(ByteToRead, 1, pos, fp);
      cout << "读取到的字节数:" << num << endl;
      nRet = fclose(fp);
      fp = NULL;
    
      cout << "=============================" << endl;
    
      fp = fopen("D:\\test02.txt", "wb");
      num = fwrite(ByteToWrite, 1, strlen(ByteToWrite), fp);
      cout << "写入的字节数:" << num << endl;
      fclose(fp);
    
      memset(ByteToRead, 0, sizeof(ByteToRead));
      fp = fopen("D:\\test02.txt", "rb");
    
      pos = 0;
      fseek(fp, 0, SEEK_END);
      fgetpos(fp, &pos);
      fseek(fp, 0, SEEK_SET);
      cout << "文件实际包含的字节数:" << pos << endl;
    
      num = fread(ByteToRead, 1, pos, fp);
      cout << "读到的字节数:" << num << endl;
      fclose(fp);
    }

运行结果如下图所示:

在这里插入图片描述

使用notepad++来观察两文件的十六进制显示:

在这里插入图片描述
观察发现以不带"b"的方式访问文件会写入0x0d,也不会读出0x0d。这里解释一下,如果不带"b"则以文本方式访问文件即:
“w”=“wt”,“r”=“rt”。而windows下对文本中的’\n’,会处理成"\r\n",即0x0d0a,相关文章可参考:

https://blog.csdn.net/qq_40395278/article/details/81199281

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值