TianRB
TianRB

Reputation: 691

File doesn't gets writen with data despite it being the same as the other that does work

I'm working on a project for a class. It should fill an array with random numbers from 0 to maxNum, remember the biggest, get an avarage and then copy the data on 2 binary files. Here's the relevant part:

FILE *pf, *rf;
int numCant = 50, maxNum = 100;
int n, i, avg = 0, m = 0;
pf = fopen("file.dat", "wb+");
rf = fopen("backupFile.dat", "wb+");
srand( floor(time( NULL )));

for (i = 0; i < numCant; i++) {
    n = rand() % maxNum;
    avg += n;
    if (m < n)
        m = n;
    fwrite(&n, sizeof(int), 1, pf);
    fwrite(&n, sizeof(int), 1, rf);
}

This works perfectly for the first file (fp) but for some reason the second file (rf) wont save anything. The file will be created but remain empty. Can someone explain to me the diference between pf and rf so that only one works?

Upvotes: 1

Views: 46

Answers (3)

TianRB
TianRB

Reputation: 691

Apparently OSX Finder handles files strangely, the file showed as "Zero bytes" when viewed on Finder (File explorer), but the data was inside when I opened the file with a text editor. Should I delete the question since the code was not my problem after all?

Upvotes: 0

Clyde D&#39;Cruz
Clyde D&#39;Cruz

Reputation: 2065

You need to close the files after the write operation.

fclose (pf);
fclose(rf);

Upvotes: 0

Iharob Al Asimi
Iharob Al Asimi

Reputation: 53006

Just add fflush() after each fwrite(), like this

fwrite(&n, sizeof(int), 1, pf);
fflush(pf);

fwrite(&n, sizeof(int), 1, rf);
fflush(rf);

also, remember to fclose() each file when you finish, and check that fopen() didn't return NULL, it's not guaranteed that openning a file for writing will succeed.

Upvotes: 2

Related Questions