生成可重复利用的测试目录

ChenQi 发布于 2012/11/12 13:22
阅读 128
收藏 0

我们经常写一些对文件和文件夹的操作,比如遍历某个文件夹。如何确保我们写的代码可靠?我们需要一个可以重复利用的目录,来测试代码。

The Practice of Programming 中说:

“When Steve Bourne was writing his Unix shell (which came to be known as the
Bourne shell), he made a directory of 254 files with one-character names, one for each
byte value except '\0' and slash, the two characters that cannot appear in Unix file
names. He used that directory for all manner of tests of pattern-matching and tok-
enization. (The test directory was of course created by a program.) For years after-
wards, that directory was the bane of file-tree-walking programs; it tested them to
destruction.”

我觉得这个方法很好,所以在此分享下。

另外,附上一段简单的自动生成此目录的代码:

#include <stdio.h>
#include <sys/stat.h>
#include <sys/types.h>

void create_dir(const char *dirname) {
	int ret = mkdir(dirname, 0755);
	if (ret != 0) {
		perror("create failed");
	}
}

int main(int argc, char *argv[]) {
	unsigned char dirname[2] = {0};
	int i;
	unsigned char uc;
	for (i=0; i<256; i++) {
		uc = (unsigned char)i;
		if (uc != '\0' && uc != '/') {
			dirname[0] = uc;
			create_dir(dirname);
		}
	}
}



加载中
返回顶部
顶部