如果我有一对长函数:
#include <stdio.h>
#include <stdlib.h>
void writeData()
{
FILE *fp; int someVar1 = 1; int someVar2 = 2; int someVar3 = 3;
fp = fopen("results.dat", "a"); // open file
if (fp == NULL) {
printf("I couldn't open results.dat for appending.\n");
exit(0);
}
fprintf(fp, "%d\n", someVar1); // write to file
fprintf(fp, "%d\n", someVar2); // write to file
fprintf(fp, "%d\n", someVar3); // write to file
fclose(fp); // and close
}
void readData()
{
FILE *fp; int someVar1, someVar2, someVar3;
fp = fopen("results.dat", "r"); // open file for reading
if (fp == NULL) {
printf("I couldn't open results.dat for reading.\n");
exit(0);
}
fscanf(fp, "%d\n", &someVar1); // read from file
fscanf(fp, "%d\n", &someVar2); // read from file
fscanf(fp, "%d\n", &someVar3); // read from file
fclose(fp); // and close
printf("someVar: %d %d %d\n", someVar1, someVar2, someVar3);
}
int main(void)
{
writeData();
readData();
return 0;
}
有没有办法可以(ab)使用预处理器来避免重复读写代码?换句话说,有没有办法在 and 中生成一对fprintf(fp, "%d\n", someVar)
和fprintf(fp, "%d\n", someVar)
write()
read()
函数
编辑:这同样适用于分配/释放整个内存负载,例如http://pastebin.com/wdAnHfWx。基本上任何在两个互补但简单的函数之间有大量代码重复的任务。