简体   繁体   中英

_read from stdin in Visual studio 2015

reading from the console with

i = _read(_fileno(stdin), &c, 1);

behaves differently in VS 2013 and VS2015, when the last character of an input word has been read, and the 'return' key is due. Upon calling the line again

in VS2013 (and older versions) c will become 10 (end of line), and _read returns 1 (one byte read)

In VS2015 c will again be 10 , but _read returns 0

Bug or feature ?

The following small console program shows some details:

// ConsoleApplication1.c

#include <stdio.h>
#include <io.h>
#include <errno.h>
#include <fcntl.h>

int main()
{
    char c;
    int i, j;
    char buf[128], buf2[128];

    /* in 2015 this will return 0 at reading '\n' */
    /* bug ? */
    _setmode(_fileno(stdin), _O_TEXT);
    /* this will return 1 at reading '\n' */
    //_setmode(_fileno(stdin), _O_BINARY);

    j = 0;
    printf("Input:\n");

    /* read characters from stdin until \n is hit */
    do {
        /* 3 lines excerpted from original program (ngspice simulator)*/
        do
            i = _read(_fileno(stdin), &c, 1);
        while (i == -1 && errno == EINTR);
        /**************************************************************/
        if (i==0)
            buf2[j] = '0';
        else if (i == 1)
            buf2[j] = '1';
        else
            buf2[j] = 'x';

        buf[j++] = c;

    } while (c != '\n');

    buf[j] = '\0';
    buf2[j] = '\0';
    /* repeat the input */
    printf("%s\n", buf);
    /* type return value of _read */
    /* last caracter is 0 in VC2015 and 1 in VC2013 */
    printf("%s\n", buf2);
    /* wait for user 'return' */
    getchar();
    return 0;
}

With VC2010 (and 2008, 2013) the output is

Input:
asdfghj
asdfghj

11111111

With VC2015 I get

Input:
asdfghj
asdfghj

11111110

错误,由Microsoft修复,用于下一个Visual Studio 2015 CRT版本

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM