【问题标题】:How to use .in and .out files for testing in a unix environment?如何在 unix 环境中使用 .in 和 .out 文件进行测试?
【发布时间】:2025-11-27 19:40:01
【问题描述】:

我有 C++ 程序,以及一堆用于预制测试的 .in 和 .out 文件。我想知道如何执行我的 c++ 程序并将它们输入其中。

【问题讨论】:

  • 打开终端,输入g++ program.cpp进行编译。然后输入$./a.out < test.in。手动或使用 diff 将输出与 test.out 进行比较(输入 man diff 以了解有关 diff 的更多信息)
  • 如果我有一个包含多个 .in 和 .out 文件的 tar.gz 文件,有没有办法同时运行它们?在其中一个测试文件夹中,我还获得了一个 runtests.bash 文件。我该如何运行它?
  • 无法同时运行所有文件。您可以按顺序运行脚本。
  • 检查是否有某种自述文件(或类似名称)。检查test目录的内容,阅读runtests.bash文件,它可能包含一些关于如何运行测试的线索......

标签: c++ input output


【解决方案1】:

我假设您有一个文件列表,例如 test0.in 和对应的 test1.out。也许你想要这样的 Makefile:

#Put rules/variables to actually make the program

SRC = test.cpp
TARGET = program

INPUTS = $(shell ls *.in)
OUTPUTS = $(patsubst %.in, %.out, $(INPUTS))
TESTS = $(patsubst %.in, %.test, $(INPUTS))

#This build rule is just for showcase.  You will probably need your own, more sophisticated build rules
$(TARGET): $(SRC)
    g++ $^ -o $@ -std=c++11

.PHONY: test
test: $(TESTS)

%.test : %.in %.out $(TARGET)
    @./$(TARGET) < $*.in > $@;
    @if cmp -s $@ $*.out; then \
        echo "PASS: $*"; \
    else \
        echo "FAIL: $*"; \
    fi
    @rm $@

然后,只需键入 make test -j 即可进行多线程测试。

【讨论】: