请向我解释C程序

时间:2013-09-10 15:43:39

标签: c

我正在阅读这本书Windows System Programming。在第二章中,有一个程序Cat.c。它实现了linux的cat命令。代码为http://pastebin.com/wwQFp599

以下是令我困惑的部分:

/*      iFirstFile is the argv [] index of the first input file. */
iFirstFile = Options (argc, argv, _T("s"), &dashS, NULL);

if (iFirstFile == argc) { /* No files in arg list. */
        CatFile (hStdIn, hStdOut);
        return 0;
} 

如评论iFirstFile中所述,是第一个输入文件的argv []索引。

这意味着如果我尝试cat -s abc.txt,然后iFirstFile = 2,而是argc == 3

我想不出在什么情况下iFirstFile == argc?我无法理解它背后的逻辑。谁能解释我这部分呢?

2 个答案:

答案 0 :(得分:4)

就像在评论中所说的那样,如果argv中没有文件名,则Options()返回argc。所以这就是你想要stdin而不是文件的情况。

if (iFirstFile == argc) { /* No files in arg list. */
        CatFile (hStdIn, hStdOut);
        return 0;
} 

例如,“cat> x”从stdin读取。 “foo | cat | bar”也是如此。在每种情况下,Options()都会返回argc;

答案 1 :(得分:1)

如果您运行程序:

cat

然后argc == 1iFirstFile == 1。因此if语句条件为true,它将使用stdinstdout运行,允许使用管道或交互式输入,或输出到终端窗口。