以下内容将创建一个随机数表并将其打印到控制台上。如何修改我创建的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;
}

最佳答案

此版本与printf()语句一起完成:(请参见下面的createtxt()
在printf语句之前打开文件:

FILE* ofp = createtxt("myrandom.txt");
char buf[20];


rn = rand() % SHAPE_RANGE;
sprintf(buf, "\t%4d",rn);//use sprintf() to put information into buf
printf(buf);             //output to stdout
fputs(buf, ofp );        //output to file
/// repeat lines for X_RANGE, Y_RANGE, etc.

fclose(ofp);


如果来自createtxt:

将原型更改为int createtxt(char *fnam, char *buf)

而不是使用

sprintf(buf, "\t%4d",rn);//use sprintf() to put information into buf
printf(buf);             //output to stdout


采用:
    //创建并初始化更大的缓冲区。

char buf[1000];  //or some other appropriately sized buffer

buf[0]=0;  //set NULL to first position of buf
//then, between all the printf statements in main, call this:
sprintf(buf, %s\t%4d", buf, rn);//will concatenate all bufs until end


然后将buf作为参数传递给createtxt()

void createtxt(char* fnam, char *buf)
{
    FILE* ofp;
    ofp = fopen(fnam, "w");
    if (ofp == NULL) {
        printf("Cannot open output file %s\n", fnam);
        exit(EXIT_FAILURE);
    {
    fputs(buf, ofp);
    fclose(ofp);
}

09-08 01:08