stdout重定向更改输出

oad*_*ams 6 c unix

我有一个叫做的程序abc.

当我运行以下命令时:

$ ./abc < infile
Run Code Online (Sandbox Code Playgroud)

我得到以下输出:

ijklm
Run Code Online (Sandbox Code Playgroud)

但是,当我跑:

$ ./abc < infile > outfile
$ cat outfile
Run Code Online (Sandbox Code Playgroud)

我得到了这个输出:

ijkoo
Run Code Online (Sandbox Code Playgroud)

现在,我假设这是我的程序的一个错误.但是,无论我的程序在做什么,我都不知道这是怎么回事.

编辑:

现在我知道这是可能的,我很好奇我的程序中是什么导致了这一点.

我的程序中的循环内有一个块,其中包含:

byte = ascii_to_byte(asciibyte);
putchar(byte);
Run Code Online (Sandbox Code Playgroud)

byte是类型的char.

现在,如果我改变putchar(byte)printf("%c", byte)所有的输出保持不变.

但是,如果我将其更改为printf("%d", byte),则$ ./abc < infile输出:

105106107111111
Run Code Online (Sandbox Code Playgroud)

这是那些ascii字符的十进制表示形式outfile.但它们并不是角色的十进制表示,因为它们刚刚被发送到stdout时实际出现了.我不明白为什么会有这种差异.

编辑#2:

如果我将打印行更改为printf("%c\n", byte),则$ ./abc < infile输出:

i
j
k
o
o
Run Code Online (Sandbox Code Playgroud)

这与outfile中的内容一致.再次,不知道有什么区别.

编辑#3

我刚刚在32位机器上测试了这个,程序工作正常:outputfile包含ijklm.奇怪的.

编辑#4

这是主要功能:

int main()
{
    char asciibyte[8];
    char byte;

    int c; //Using int to avoid the EOF pitfall.
    long charcount = 0;

    while((c = getchar()) != EOF){
        if(c != '0' && c != '1'){
            continue;
        }
        asciibyte[charcount % 8] = c;
        if(charcount % 8 == 7){
            /*Testing revealed that at this point asciibyte does contain
            what it should contain, eight ASCII ones and zeros representing
            a byte read in from stdin*/
            byte = ascii_to_byte(asciibyte);
            /*Print statements such as:
                printf("%d", byte);
                printf("%c\n", byte);
            reveal that the ascii_to_byte function works incorrectly on my
            64 bit machine. However these statements:
                putchar(byte);
                printf("%c", byte);
            make it appear as though the function operates as it should.
            EXCEPT if i redirect that output to a file.*/
            putchar(byte);
        }
        charcount++;
    }
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

这是ascii_to_byte函数:

char ascii_to_byte(char *asciibyte){
    char byte;
    int i;
    for(i = 0; i < 8; ++i){
        if(asciibyte[7-i] == '1'){
            byte = byte | (1 << i);
        }
    }
    return byte;
}
Run Code Online (Sandbox Code Playgroud)

最终编辑

我注意到我应该将字节初始化为0x00.问题解决了.我为什么这么迟钝?我会给那些能够具体解释这是如何导致问题的人给出答案.

小智 1

这当然是可能的 - 程序可以检查它是否正在写入终端并写入与写入管道时写入的内容不同的内容。