是否可以计算程序在C中运行的次数? 我需要设置一个计数器吗?例如:
#include <stdio.h>
int main()
{
int var1;
scanf("%d", &var1);
int var2;
scanf("%d", &var2);
int var3;
var3 =var1 + var2;
printf("The answer is = %d" , var3);
/* if (The program ran for more than two times) {
printf("The program is only allowed to run once or twice\n");
}
else {
printf("The answer = %d" , var3);
}*/
return 0;
}
如果程序已经运行了两次,程序将显示错误消息一次并重新开始计数。
答案 0 :(得分:1)
我们可以将this answer与一些简单的文件IO结合起来,以达到预期的效果。
请注意,这仅 一个如何计算程序运行次数的示例。如果没有仔细考虑本答案下面评论中提到的问题,请不要在任何安全敏感的环境中使用它。
#include <unistd.h>
#include <sys/file.h>
#include <stdio.h>
int main(){
int myCounterFd;
if ((myCounterFd = open ("/tmp/myappname.counter", O_CREAT | O_RDWR, 0666)) < 0) {
return -1;
}
if (flock (myCounterFd, LOCK_EX | LOCK_NB) < 0) {
return -1;
}
FILE* fp = fdopen(myCounterFd, "w+");
int count;
size_t error;
error = fread(&count, sizeof(count), 1, fp);
printf("Error = %zu\n", error);
// The program has never been run before
if (error < 1) {
count = 1;
fwrite(&count, sizeof(count), 1, fp);
} else{
count++;
rewind(fp);
fwrite(&count, sizeof(count), 1, fp);
}
fflush(fp);
printf("Program has now been run %d times.\n", count);
flock (myCounterFd, LOCK_UN);
close(myCounterFd);
}