下面创建一个随机数表并将其打印到控制台上。如何修改我做的createtxt函数,让控制台上的输出同时生成一个文本文件。
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
FILE* createtxt(char* fnam){
FILE* ofp;
ofp = fopen(fnam, "w");
if (ofp == NULL) {
printf("Cannot open output file %s\n", fnam);
exit(EXIT_FAILURE);
}
void closetxt(FILE* ofp){
fclose(ofp);
}
int main (void){
printf("Table of random numbers for drawing geometric shapes in different colours, sizes and opacities\n");
int rn = 0;
unsigned int seed = (unsigned int)time(NULL);
srand(seed);
int k = 0;
printf("shape#\tRSCE\tx\ty\twidth\theight\tred\tgreen\tblue\tgreen\topacity\n");
while (k < NO_SHAPES){
printf("%6d", k);
rn = rand() % SHAPE_RANGE;
printf( "\t%4d",rn);
rn = rand() % X_RANGE;
printf("\t%d",rn);
rn = rand() % Y_RANGE;
printf("\t%d",rn);
rn = rand() % WIDTH_RANGE;
printf("\t%5d",rn);
rn = rand() % HEIGHT_RANGE;
printf("\t%6d",rn);
rn = rand() % RED_RANGE;
printf("\t%3d",rn);
rn = rand() % GREEN_RANGE;
printf("\t%5d",rn);
rn = rand() % BLUE_RANGE;
printf("\t%4d",rn);
rn = rand() % OPACITY_RANGE;
printf("\t%.1f\n",rn/100.0);
k++;
}
FILE* ofp = createtxt("myrandom.txt")
closetxt(ofp);
return EXIT_SUCCESS;
}