您的位置:首页 > 运维架构

fopen的按文本读写和按二进制读写

2018-01-30 21:31 218 查看
二进制读写和文本读写的区别:

1. 二进制方式很简单,读文件时,会原封不动的读出文件的全部內容,写的時候,也是把內存缓冲区的內容原封不动的写到文件中。而‘\n’ 在ascii码中是’0x0A’。

2. 而文本方式就不一样了,在写文件时,会将换行符号‘\n’会转化为系统相应的ascii码,所以,在linux下,会把换行符转化为linux 的换行 ‘0x0A’ ;在windown下,会把换行符转化为‘0x0D 0x0A’。

加入,有下面代码

nt main( )
{

char he[20] = "hello world\n";
FILE *outfile = fopen("t.txt", "wt");
fwrite(he, sizeof(char), 20, outfile);
fclose(outfile);

outfile = fopen("b.txt", "wb");
fwrite(he, sizeof(char), 20, outfile);
fclose(outfile);

return 0;
}


在linux下运行,分别按文本生成t.txt,按二进制生成b.txt,用hexdump -C命令查看,如下:

tl@tl-vm:~/program/c/test_in_clion/cmake-build-debug$ hexdump b.txt -C
00000000  68 65 6c 6c 6f 20 77 6f  72 6c 64 0a 00 00 00 00  |hello world.....|
00000010  00 00 00 00                                       |....|
00000014
tl@tl-vm:~/program/c/test_in_clion/cmake-build-debug$ hexdump t.txt -C
00000000  68 65 6c 6c 6f 20 77 6f  72 6c 64 0a 00 00 00 00  |hello world.....|
00000010  00 00 00 00                                       |....|
00000014


在vs2013下运行,产生相应文件

t.txt如下:



b.txt如下:



总结:

二进制标志,文本标志,在linux下是没有影响的,因为两种情况下,‘\n’都是‘0x0A’。

而在windown下,二进制是转化为’0x0A’ ,文本是转化为’0x0D 0x0A’。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐