从标准输入读取输入参数时的意外行为
Unexpected behavior when reading input parameters from stdin
我正在测试一个程序 "myprog.c" 如果它使用任何输入参数运行就会崩溃:
#include <stdlib.h>
int main(int argc, char * arg[]){
if (argc > 1 ){
abort();
}
}
正如预期的那样,“./myprog.out abc”崩溃了。但后来我尝试从文件中获取输入:“./myprog.out < inputs.txt”,其中 inputs.txt 有几个词,程序不会崩溃。为什么不?
那是因为 shell 没有将 < inputs.txt
作为参数传递。相反,shell 使得 inputs.txt
的内容将从 stdin
.
中读取
因为argc等于1,可以用下面的代码验证:
int main(int argc, char * arg[])
{
printf("argc = %i\n", argc);
if (argc > 1 ) {
abort();
}
}
输出:
argc = 1
它出现是因为你不能像这样传递参数,如果你用 < 你的程序会像它提供的那样解释它 stdin (filedescriptor numero 0)
如果你想传递比 1 个更多的参数,请点赞:
./a.out abc def ghi
如果要通过文件获取 "argument",请使用 getline
我正在测试一个程序 "myprog.c" 如果它使用任何输入参数运行就会崩溃:
#include <stdlib.h>
int main(int argc, char * arg[]){
if (argc > 1 ){
abort();
}
}
正如预期的那样,“./myprog.out abc”崩溃了。但后来我尝试从文件中获取输入:“./myprog.out < inputs.txt”,其中 inputs.txt 有几个词,程序不会崩溃。为什么不?
那是因为 shell 没有将 < inputs.txt
作为参数传递。相反,shell 使得 inputs.txt
的内容将从 stdin
.
因为argc等于1,可以用下面的代码验证:
int main(int argc, char * arg[])
{
printf("argc = %i\n", argc);
if (argc > 1 ) {
abort();
}
}
输出:
argc = 1
它出现是因为你不能像这样传递参数,如果你用 < 你的程序会像它提供的那样解释它 stdin (filedescriptor numero 0)
如果你想传递比 1 个更多的参数,请点赞:
./a.out abc def ghi
如果要通过文件获取 "argument",请使用 getline