fgets的回车 [英] carriage return by fgets

查看:87
本文介绍了fgets的回车的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在运行以下代码:

#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包含:我是男孩\ r \ n

text.txt contains: I am a boy\r\n

因为我在Windows上,所以它以\ r \ n作为换行符,因此,如果我从文件中读取该字符,则应该在其中存储我是男孩\ n \ 0" str ,但我得到我是男孩\ r \ n" .我正在使用mingw编译器.

Since I am on Windows, it takes \r\n as a new line character and so if I read this from a file it should store "I am a boy\n\0" in str, but I get "I am a boy\r\n". I am using mingw compiler.

推荐答案

由于我使用的是Windows,因此它将\ r \ n作为换行符...

Since I am on Windows, it takes \r\n as a new line character...

这个假设是错误的.C标准将回车和换行符视为两个不同的事物,如C99§5.2.1/3(字符集)所示:

This assumption is wrong. The C standard treats carriage return and new line as two different things, as evidenced in C99 §5.2.1/3 (Character sets):

[...]在基本执行字符集中,应有控制字符,它们表示警报,退格键,回车符和换行符.[...]

[...] In the basic execution character set, there shall be control characters representing alert, backspace, carriage return, and new-line. [...]

fgets 函数描述如下,在C99§7.19.7.2/2中:

The fgets function description is as follows, in C99 §7.19.7.2/2:

fgets函数读取的字符数最多少于n指定的字符数从stream指向的流到s指向的数组.没有其他在换行符(保留)或文件结束后读取字符.一种在将最后一个字符读入数组后,立即将空字符写入.

The fgets function reads at most one less than the number of characters specified by n from the stream pointed to by stream into the array pointed to by s. No additional characters are read after a new-line character (which is retained) or after end-of-file. A null character is written immediately after the last character read into the array.

因此,当遇到字符串我是男孩\ r \ n 时,符合规范的实现应读取到 \ n 字符.没有任何理智的理由可以使实现基于平台放弃 \ r .

Therefore, when encountering the string I am a boy\r\n, a conforming implementation should read up to the \n character. There is no possibly sane reason why the implementation should discard \r based on the platform.

这篇关于fgets的回车的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆