1 #include <stdio.h>
2
3 int main(int argc, char *argv[])
4 {
5 char he[20] = "hello world\n";
6
7 FILE *outfile = fopen("t.txt", "wt");
8 fwrite(he, sizeof(char), 20, outfile);
9 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.txt,fopen会将0d0a替换为0a
第二行,以文本方式打开b.txt,返回原内容
第三行,以二进制方式打开t.txt,fopen不作替换,直接读取0d0a
第四行,以二进制方式打开b.txt,返回原内容
总结: 就是在处理“\n”是有所不同