-2

我很难用 C 语言编写一个函数来检查用户输入的文件(通过stdin)是否存在。例如,如果程序运行为./a.out <myfile.txt,如果此文件不存在,我希望它返回 false 。我可以通过将文件作为参数传递(即./a.out myfile.txt)使用fopen()来做到这一点,但不确定如何使用'stdin'(即./a.out <myfile.txt

好的澄清:

较大的程序应该获取文本文件的内容并对其执行操作。该程序必须在命令行中以./a.out arg1 arg2 <myfile.txt. 如果用户以./a.out arg1 arg2or运行程序./a.out(即未指定要对其执行操作的文件),我想提示用户包含一个文件(使用 stdin <,而不是作为参数传递)。

4

5 回答 5

3

标准输入可能根本不是来自文件。即使是这样,当用户在命令行键入“< myfile.txt”时,shell 会吞下该部分命令,并且永远不会将其传递给程序。就程序而言,它是一个匿名的字节流,可能来自文件、设备、终端、管道或其他东西。可以查询你有哪些,但即使你知道它是一个文件,你也不会得到命令行上给出的文件名,只有一个 inode。

于 2013-05-18T06:07:08.803 回答
2

由于 shell 负责打开文件进行重定向,因此如果文件未打开,它将拒绝执行命令。

于 2013-05-18T06:04:07.733 回答
2

输入重定向是由shell 完成的,而不是你的程序。它只是将文件附加到标准输入。

因此,如果您尝试从不存在的文件重定向输入,shell应该会抱怨,甚至不会运行您的程序,如下面的脚本所示:

pax> echo hello >qq.in

pax> cat <qq.in
hello

pax> cat <nosuchfile.txt
bash: nosuchfile.txt: No such file or directory

无论如何,您的程序通常不知道输入来自哪里,因为您可以执行以下操作:

echo hello | cat

其中涉及文件。


如果您希望您的程序检测文件的存在,它必须打开文件本身,这意味着您可能应该将文件名作为参数而不是使用标准输入。

或者,您可以在运行程序之前检测文件是否存在,如下所示bash

fspec=/tmp/infile
if [[ -f ${fspec} ]] ; then
    my_prog <${fspec}
else
    echo What the ...
fi
于 2013-05-18T06:05:02.637 回答
1

操作系统阻止调用您的程序,因为它可以提供有效的stdinifmyfile.txt不存在。您的程序将不会运行,因此您无法发出文件丢失的信号,并且此诊断是在操作系统级别完成的。

于 2013-05-18T06:04:34.143 回答
0

If user ran the program as ./a.out arg1 arg2 or ./a.out (i.e not specifying the file to perform actions on), I want to prompt the user to include a file (using stdin <, not passed as an argument).

You could use OS-specific functions to check whether stdin is terminal. Checking whether it's file is a very bad idea, because it's very useful to pipe into stdin ... in fact, that's a major reason that there is such a thing as stdin in the first place. If you only want to read from a file, not a terminal or pipe, then you should take the file name as a required argument and not read from the orginal stdin (you can still read from stdin by using freopen). If you insist that you don't want to do it that way, then I will insist that you want to do it wrong.

于 2013-05-18T07:19:37.777 回答