对拍程序
借鉴sandy老哥的对拍程序
https://www.cnblogs.com/sandychn/p/10355239.html
1 #include <cstdio> 2 #include <cstring> 3 #include <cstdlib> 4 #include <cerrno> 5 #include <ctime> 6 7 // 设置区 8 namespace Settings { 9 const int MAX_LEN = 20; // 当发现错误时,显示错误行数据的最大长度 10 const int CASE_CNT = 100; // 对拍测试次数 11 const int BUFFER_SIZE = 1 << 10; // 每行的缓冲区大小 12 const char *const userFile = "1.cpp"; // 需要测试的源代码文件名(相对路径) 13 const char *const stdFile = "2.cpp"; // 标准答案的源代码文件名(相对路径) 14 const char *const dataFile = "3.cpp"; // 随机生成数据的源代码文件名(相对路径) 15 } 16 17 using namespace Settings; 18 using namespace std; 19 char cmd[BUFFER_SIZE], info[BUFFER_SIZE * 3]; 20 char buf1[BUFFER_SIZE], buf2[BUFFER_SIZE]; 21 22 template <typename ...T> 23 int run(const char *str, T ...args) { 24 sprintf(cmd, str, args...); 25 return system(cmd); 26 } 27 28 bool fileCompare(const char *stdOutput, const char *userOutput) { 29 FILE *fp_std = fopen(stdOutput, "r"), *fp_user = fopen(userOutput, "r"); 30 if (fp_std == nullptr || fp_user == nullptr) { 31 sprintf(info, "Open file failed: %s\n", strerror(errno)); 32 return false; 33 } 34 bool flag = false; 35 for (int i = 1; !feof(fp_std) && !feof(fp_user); ++i) { 36 char *p1 = fgets(buf1, BUFFER_SIZE, fp_std); 37 char *p2 = fgets(buf2, BUFFER_SIZE, fp_user); 38 if (p1 == nullptr && p2 == nullptr) { 39 flag = true; 40 break; 41 } else if (!p1 || !p2 || strcmp(p1, p2)) { 42 sprintf(info, 43 "Difference found in line %d:\n std: %.*s user: %.*s", 44 i, MAX_LEN, p1 ? p1 : "(EOF Detected)\n", 45 MAX_LEN, p2 ? p2 : "(EOF Detected)\n"); 46 break; 47 } 48 } 49 fclose(fp_std), fclose(fp_user); 50 return flag; 51 } 52 53 int main() { 54 printf("Compiling... "); 55 run("g++ %s -o user.exe", userFile); 56 run("g++ %s -o std.exe", stdFile); 57 run("g++ %s -o data.exe", dataFile); 58 printf("Finished.\n"); 59 clock_t st, ed; 60 for (int i = 1; i <= CASE_CNT; ++i) { 61 printf("Case %03d: ", i); 62 run("data.exe >data.txt"); 63 run("std.exe <data.txt >std.txt"); 64 st = clock(); 65 int ret = run("user.exe <data.txt >user.txt"); 66 if (ret) { 67 printf("Runtime Error - Exit code is %d\n", ret); 68 break; 69 } 70 ed = clock(); 71 if (!fileCompare("std.txt", "user.txt")) { 72 printf("Wrong Answer.\n------------------------------\n"); 73 puts(info); 74 printf("------------------------------\nNote: At most %d characters will be shown for both lines.\n", MAX_LEN); 75 printf("Press anykey to exit.\n"); 76 getchar(); 77 break; 78 } else { 79 printf("Accepted. Time: %dms.\n", int(ed - st)); 80 } 81 } 82 return 0; 83 }