我需要避免错误的输入/输出文件名以及无效的参数。我也使用过类似的东西,但它并没有真正帮助:
while ((c = getopt(argc, argv, "i:o:")) != -1) {
switch (c) {
case 'i':
inFile = strdup(optarg);
break;
case 'o':
outFile = strdup(optarg);
break;
default:
//usage(argv[0]);
break;
}
}
if ((ptr1 = fopen(inFile, "r+")) == NULL) {
fprintf(stderr, "Error: cannot open file %s\n", inFile);
exit(-1);
}
if ((ptr = fopen(outFile, "w+")) == NULL) {
fprintf(stderr, "Error: cannot open file %s\n", outFile);
exit(-1);
}
测试我的程序的python程序如下:
class Arg2(Test):
name = "arg2"
description = "bad arguments"
timeout = 5
def run(self):
self.runexe(["fastsort", "a", "b", "c", "d"],
stderr = usage_error, status = 1)
self.done()
class Badin(Test):
name = "badin"
description = "bad input file"
timeout = 5
def run(self):
invalid = mktemp(prefix='/invalid/path/')
self.runexe(["fastsort", "-i", invalid, "-o", "outfile"],
stderr = "Error: Cannot open file {0}\n".format(invalid), status = 1)
self.done()
class Badout(Test):
name = "badout"
description = "bad output file"
timeout = 5
def run(self):
infile = self.project_path + "/infile"
# create a valid (empty) input file
open(infile, "a").close()
invalid = mktemp(prefix='/invalid/path/')
self.runexe(["fastsort", "-i", infile, "-o", invalid],
stderr = "Error: Cannot open file {0}\n".format(invalid), status = 1)
self.done()
您能否给我一些提示和代码片段来避免错误文件名/错误文件路径以及 C 中的无效参数处理的常用方法?