尽管这个问题已经得到解答并得到了清楚的解释,但我认为用一个简单的代码示例来展示主要问题(\n 和 \r\n 之间的翻译)会很有趣。请注意,我没有解决文件末尾的 Crtl-Z 字符的问题。
#include <stdio.h>
#include <string.h>
int main() {
FILE *f;
char string[] = "A\nB";
int len;
len = strlen(string);
printf("As you'd expect string has %d characters... ", len); /* prints 3*/
f = fopen("test.txt", "w"); /* Text mode */
fwrite(string, 1, len, f); /* On windows "A\r\nB" is writen */
printf ("but %ld bytes were writen to file", ftell(f)); /* prints 4 on Windows, 3 on Linux*/
fclose(f);
return 0;
}
如果您在 Windows 上执行该程序,您将看到打印以下消息:
As you'd expect string has 3 characters... but 4 bytes were writen to file
当然,您也可以使用 Notepad++ 之类的文本编辑器打开文件,然后查看自己的字符:
![在此处输入图像描述](https://i.stack.imgur.com/p3uAB.png)
在以文本模式读取文件时,在 Windows 上执行逆变换。