我正在运行以下代码:
#include<stdio.h>
#include<string.h>
#include<io.h>
int main(){
FILE *fp;
if((fp=fopen("test.txt","r"))==NULL){
printf("File can't be read\n");
exit(1);
}
char str[50];
fgets(str,50,fp);
printf("%s",str);
return 0;
}
text.txt 包含:I am a boy\r\n
因为我在 Windows 上,它需要\r\n 作为换行符,所以如果我从文件中读取它应该存储 "I am a boy\n\0"
在str
,但我得到 "I am a boy\r\n"
。我正在使用 mingw 编译器。
最佳答案
行为取决于 c 库实现以及您传递给 fopen
的模式。请参阅有关 fopen
(fopen on MSDN) 的 MSDN 文档中的引用:
b - Open in binary (untranslated) mode; translations involving carriage-return and linefeed characters are suppressed.
意思是,如果您使用 Microsoft c 库,并且打开您的文件时省略“b”,回车符将从流中删除。
由于您使用的是 mingw,您的编译器可能会链接到遵循 POSIX 标准的 GNU c 库。这就是 GNU 文档中关于 fopen
(fopen on gnu.org) 的内容:
The character ‘b’ in opentype has a standard meaning; it requests a binary stream rather than a text stream. But this makes no difference in POSIX systems (including GNU systems).
结论:您省略了 'b' 模式字符,它以文本模式打开您的流。您在 Windows 上,但使用 GNU c 库,它在文本模式和二进制模式之间没有区别。这就是 fgets
读取回车符和换行符的原因。
关于fgets 回车,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12769289/