参考:http://blog.csdn.net/hinyunsin/article/details/6401854
#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); outfile = fopen("b.txt", "wb"); fwrite(he, sizeof(char), 20, outfile); fclose(outfile); return 0; }
用WinHex查看本地的两个文件
t.txt
b.txt
可以看到按文本写时 fopen 把 '\n' 替换为了 0D0A
对应的,读文件时
#include <stdio.h> #include <string.h> void echo(char *sz) { int i = 0; while(sz[i]) { printf("%x ", sz[i]); ++i; } printf("\n"); } int main(int argc, char *argv[]) { char he[20]; FILE *infile = fopen("t.txt", "rt"); fread(he, sizeof(char), 20, infile); echo(he); fclose(infile); infile = fopen("b.txt", "rt"); fread(he, sizeof(char), 20, infile); echo(he); fclose(infile); infile = fopen("t.txt", "rb"); fread(he, sizeof(char), 20, infile); echo(he); fclose(infile); infile = fopen("b.txt", "rb"); fread(he, sizeof(char), 20, infile); echo(he); fclose(infile); return 0; }
第一行,以文本方式打开t.txt,fopen会将0d0a替换为0a
第二行,以文本方式打开b.txt,返回原内容
第三行,以二进制方式打开t.txt,fopen不作替换,直接读取0d0a
第四行,以二进制方式打开b.txt,返回原内容