【发布时间】:2013-09-21 04:36:17
【问题描述】:
我需要避免错误的输入/输出文件名以及无效的参数。我也使用过类似的东西,但它并没有真正的帮助:
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()
您能否给我一些提示和代码 sn-p 避免错误文件名/错误文件路径以及 C 中无效参数处理的常用方法?
【问题讨论】:
-
在什么方面“没有真正帮助”?错误消息和返回值有什么问题?你想要什么不同? (尽管您可能想要记录
errno或strerror。并且您可能想要返回像1这样的正数而不是-1,因为这可能意味着您已经退出,因为您抓住了叹息。) -
另外,什么是“坏文件名”?在大多数平台上,几乎任何字符都可以出现在文件名中——在 POSIX 上,
/将被解释为路径分隔符而不是文件名的一部分,\000被解释为文件名的结尾而不是文件名的一部分,但是其他任何事情都会发生,所以没有什么要检查的。一个主要的例外是 Windows。如果您想要特定于 Windows 的错误信息,您可能希望使用CreateFile而不是fopen,但您始终可以打印出errno是什么用于fopen("a\n?*:\003", "w+")并自己找出来。
标签: python c file error-handling