二十七 fopen 中 按文本读写与按二进制读写 实例

 

 

#include <stdio.h>  

  

int main(int argc, char *argv[])  

{  

    char he[20] = "hello world\n";  

      

    FILE *outfile = fopen("t.txt""wt");  

    fwrite(he, sizeof(char), 20, outfile);  

    fclose(outfile);  

10       

11     outfile = fopen("b.txt""wb");  

12     fwrite(he, sizeof(char), 20, outfile);  

13     fclose(outfile);  

14   

15     return 0;  

16 }  


WinHex查看本地的两个文件

t.txt

b.txt

 

可以看到按文本写时 fopen 把 '\n' 替换为了 0D0A

 

对应的,读文件时

 

[cpp] view plaincopy

 

17 #include <stdio.h>  

18 #include <string.h>  

19   

20 void echo(char *sz)  

21 {  

22     int i = 0;  

23     while(sz[i])  

24     {  

25         printf("%x ", sz[i]);  

26         ++i;  

27     }  

28     printf("\n");  

29 }  

30   

31 int main(int argc, char *argv[])  

32 {  

33     char he[20];  

34       

35     FILE *infile = fopen("t.txt""rt");  

36     fread(he, sizeof(char), 20, infile);  

37     echo(he);  

38     fclose(infile);  

39       

40     infile = fopen("b.txt""rt");  

41     fread(he, sizeof(char), 20, infile);  

42     echo(he);  

43     fclose(infile);  

44       

45     infile = fopen("t.txt""rb");  

46     fread(he, sizeof(char), 20, infile);  

47     echo(he);  

48     fclose(infile);  

49   

50     infile = fopen("b.txt""rb");  

51     fread(he, sizeof(char), 20, infile);  

52     echo(he);  

53     fclose(infile);  

54   

55     return 0;  

56 }  


第一行,以文本方式打开t.txtfopen会将0d0a替换为0a

第二行,以文本方式打开b.txt,返回原内容

第三行,以二进制方式打开t.txtfopen不作替换,直接读取0d0a

第四行,以二进制方式打开b.txt,返回原内容

 

总结: 就是在处理“\n”是有所不同

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值