RoboScope
RoboScope

Reputation: 3

Writing to file issue

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

Answers (1)

M Oehm
M Oehm

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:

  • open the file in writing mode;
  • ensure that the file could be opened;
  • write to the file;
  • close the file.

Upvotes: 2

Related Questions