【发布时间】:2020-07-09 21:27:46
【问题描述】:
我有一个程序,它获取两个路径作为命令行参数。第一个参数(实际上是第二个,因为第一个是命令名本身)是程序从(输入文件)读取的文件的路径。第二个是程序写入的文件(输出文件)的路径。
int main(int argc, char *argv[])
{
int num;
/*if there are too many arguments print an error message*/
if(argc > 3)
{
perror("too many arguments");
return EXIT_FAILURE;
}
/*if there is at least one argument use it as path to input file*/
if(argc > 1)
if (!freopen(argv[1], "r", stdin)) {
perror("Path of input file is Invalid");
return EXIT_FAILURE;
}
/*if there are two arguments use the second one as output*/
if(argc == 3)
if (!freopen(argv[2], "w", stdout))
{
perror("Path of output file is Invalid");
return EXIT_FAILURE;
}
/*more code....*/
}
/*(compiled to run file "dtoa.out")*/
程序工作正常:如果提供了有效的输入和路径输出路径,它将从文件中读取和写入,如果提供的参数过多或输入文件的路径无效,程序将打印错误消息并退出。
问题在于提供了无效的输出文件路径:
$./dtoa ./tests/ExistingInput1.txt ./tests/NonExistingOutput.txt
在这种情况下,程序将只创建丢失的输出文件,而不是返回 NULL 并打印错误消息,这是不受欢迎的行为。怎么改,这样当找不到文件时,方法会返回NULL而不是新建文件?
【问题讨论】:
标签: c file error-handling stdout freopen