我正在学习流,并从教科书中复制了以下应用程序。当我的 friend 在他的Windows机器上编译并运行时,它运行得很好。当我在 Ubuntu 18.04 计算机上运行该应用程序时,输入工作正常,但这些值似乎对应用程序没有任何影响,即输入 0
不会导致程序退出。我的输出位于代码下方。
在不同机器上编译时,什么会导致不同的行为,为什么这在我的机器上不起作用?
int main(int argc, char* argv[]) { FILE *fpt; char byte; long int where,move; if(argc != 2) { printf("Usage: fileseek filename\n"); return(0); } fpt = fopen(argv[1], "r"); if(fpt == NULL) { printf("Unable to open file %s for reading\n", argv[1]); return(0); } while(1) { where = ftell(fpt); fread(&byte,1,1,fpt); fseek(fpt,-1,SEEK_CUR); printf("Byte %d: %d (%c)\n", where, byte, byte); printf("Enter #bytes (+ or -) to move, or 0 to quit: "); scanf("%d", &move); printf("move: %d\n", move); if(move == 0) break; fseek(fpt,move,SEEK_CUR); } fclose(fpt); }
Output
jonathon@dev1:~/hoover/ch5/build$ ./fileseek text.txt
Byte 0: 84 (T)
Enter #bytes (+ or -) to move, or 0 to quit: 0
move: 0
Byte 0: 84 (T)
Enter #bytes (+ or -) to move, or 0 to quit: 1
move: 1
Byte 0: 84 (T)
Enter #bytes (+ or -) to move, or 0 to quit: 2
move: 2
Byte 0: 84 (T)
Enter #bytes (+ or -) to move, or 0 to quit: 3
move: 3
Byte 0: 84 (T)
Enter #bytes (+ or -) to move, or 0 to quit: 4
move: 4
Byte 0: 84 (T)
Enter #bytes (+ or -) to move, or 0 to quit: 5
move: 5
Byte 0: 84 (T)
Enter #bytes (+ or -) to move, or 0 to quit: ^C
最佳答案
如果教科书确实如此,那就错了:%d
是 int
的转换说明符,但 move
是长整型
。正确的调用是:
scanf("%ld", &move)
,对几个 printf
调用进行了类似的更正。
它可能会巧合地工作,特别是当 long
和 int
恰好大小相同时(因为它们在 64 位 Windows 中,但在 64 位中则不然) Linux)。然而,由于不匹配,整个程序没有定义特定的行为:语言标准允许编译器假设它们所代表的那种非法行为永远不会发生,并且对于执行此类行为的程序没有任何义务一个 Action 就可以了。
关于c - 应用程序在不同机器上的行为不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62598868/