AngusTheMan
AngusTheMan

Reputation: 582

How to print function into different files in c programming

I have defined the following function in the header region,

void printArray(float list[]){        /* function decleration for printing array elements */
    int iii;
    for (iii = 0; iii < length;iii++){
        printf("%lf\n", list[iii]);
    }
    printf("\n");
}

To print this I just write printArray(x); where I have an array x[iii]=iii;

Throughout the code I want to print this into different files. So early on I want this to print to FILE *File_First_Array_Printing; with an "initialised variables" text file, while later I want it to print to FILE *File_Fourth_Array_Printing; with a "final variables" text file.

Normally when I print into files I would do something like this,

File_First_Array_Printing=fopen("Initialised-variables.txt","w");

                  fprintf(File_First_Array_Printing,"initialised array x: %f\n",printArray(x));
                                                                       /* printing the initialised arrays */
                  fclose(File_First_Array_Printing);

But it doesn't seem to like that! Please could you advise?

Upvotes: 0

Views: 2064

Answers (1)

dbush
dbush

Reputation: 223699

You should pass the FILE * to your printArray function and use that inside of the function to call fprintf:

void printArray(FILE *fp, float list[]){ 
    int iii;
    for (iii = 0; iii < length;iii++){
        fprintf(fp, "%lf\n", list[iii]);
    }
    fprintf(fp, "\n");
}

Then call it like this:

File_First_Array_Printing=fopen("Initialised-variables.txt","w");
if (!File_First_Array_Printing) {
    perror("open of Initialised-variables.txt failed");
} else {
    printArray(File_First_Array_Printing, x);
    fclose(File_First_Array_Printing);
}

Upvotes: 2

Related Questions