fgets 回车

标签 c string fgets carriage-return

我正在运行以下代码:

#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/

相关文章:

c - 是否有一个 c 函数可以获取 put as * 中的密码并存储原始值

c - 在具有换行符 : how to read all lines? 的缓冲区上使用 sscanf

javascript - 正则表达式字符串替换

C编程——sscanf读取相似行

c - 查询用户的日期,如果用户按 Enter 键,则使用今天的日期

C 无法以 txt 模式从 FILE 初始化列表

c - 如何处理来自 GCC 的 -Wconversion 警告?

c++ - 使用 AVR 微 Controller 运行 TX433 和 RX433 RF 模块

excel - VBA 中的 Unicode 字符串文字

Python 正则表达式 : I want to remove newlines after every '%}' tag close except for content in between {% verbatim%} . .. {% endverbatim %} 标签