Reputation: 3
Just trying to write to a file, the program is creating the file, but the information isn't actually writing to it. Whats being passed in isnt the issue!
void writetofile (double *A, double *B, double *C, double *D, int N)
{
int i;
for (i = 0; i <= N; i++)
{
FILE * filePtr = fopen("Output.txt", "w");
if (filePtr == NULL)
{
printf("File not found\n");
exit(1);
}
// This must be where my problem is..
fprintf(filePtr, "%f %f %f %f\n", A[i], B[i], C[i], D[i]);
}
}
Upvotes: 0
Views: 42
Reputation: 29136
You open the file inside the loop, but you should open it only once, before writing. So the code should look like this:
FILE * filePtr = fopen("Output.txt", "w");
int i;
if (filePtr == NULL) {
fprintf(stderr, "File not found\n");
exit(1);
}
for (i = 0; i < N; i++) {
fprintf(filePtr, "%f %f %f %f\n", A[i], B[i], C[i], D[i]);
}
fclose(filePtr);
Edit: In general, code to write to a file has these steps:
Upvotes: 2