我有一个名为abc
的程序。
当我运行以下命令时:
$ ./abc < infile
我得到了以下输出:
ijklm
然而,当我运行以下命令时:
$ ./abc < infile > outfile
$ cat outfile
我将得到这个输出:
ijkoo
现在,我假设这是我程序中的一个错误。然而,无论我的程序在做什么,我都不知道这是如何可能发生的。
编辑:
既然我知道这是可能的,我很想知道是我的程序中的哪一部分导致了这种情况。
我的程序中有一个包含以下内容的循环内部块:
byte = ascii_to_byte(asciibyte);
putchar(byte);
byte是char
类型。
现在,如果我将putchar(byte)
更改为printf("%c", byte)
,则所有输出都保持不变。
但是,如果我将其更改为printf("%d", byte)
,那么$ ./abc < infile
的输出如下:
105106107111111
这些ASCII字符在
outfile
中的十进制表示与它们实际发送到标准输出时的十进制表示不同。我不明白为什么会有这种差异。
编辑#2:
如果我将打印行更改为printf("%c\n", byte)
,那么$ ./abc < infile
将输出:i
j
k
o
o
这与输出到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;
}
以下是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;
}
最终编辑
我注意到我应该将byte初始化为0x00。问题解决了。为什么我这么蠢?我会给那些能够具体解释这是如何导致问题的人答案分。
./abc < infile | od -tx1
的输出是什么? - pmg0000000 69 6a 6b 6f 6f 0000005
- oadams