我有一个程序,它获取两条路径作为命令行参数。第一个参数(实际上是第二个,因为第一个是命令名本身)是程序读取的文件(输入文件)的路径。第二个是程序写入的文件(输出文件)的路径。
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
而不是创建新文件?