QUESTION 07
What does fwrite return?
2 marksAnswer
It returns the number of complete elements successfully written, not simply the total requested byte count. Check it against the requested element count.
QUESTION 07
It returns the number of complete elements successfully written, not simply the total requested byte count. Check it against the requested element count.
QUESTION 08
fread and fwrite transfer fixed-size elements between a stream and suitable memory objects.
fwrite(array, sizeof array[0], count, fp);
fread(array, sizeof array[0], count, fp);The program writes three ints, 10, 20 and 30. It reopens the file and reads exactly three ints into another array, then prints them. The native representation is used within one execution on the same implementation.
A read requesting ten records may obtain fewer because the file ends. Never loop over all ten as though the missing records had been read. A partial final record is not a complete valid record merely because some bytes were obtained. Inspect stream errors and validate file structure for a real application.
The destination must have enough actual space and a suitable type. Transferring n fixed-size elements involves O(n) element work in the ordinary analysis, plus stream costs. The fixed buffer in this example has three elements. Native binary data is implementation-dependent and should not be described as a portable database format.
This demonstration creates or replaces its codebhavya_* sample file in the working directory. Run it in a separate test directory. Native binary examples use one compatible implementation.
/* CodeBhavya | Data Structures AR25 | Learning example */
#include <stdio.h>
int main(void)
{
int input[3] = {10, 20, 30}, output[3];
FILE *fp = fopen("codebhavya_binary_demo.bin", "wb");
if (fp == NULL) { puts("Open failed"); return 1; }
if (fwrite(input, sizeof input[0], 3, fp) != 3) { fclose(fp); puts("Write failed"); return 1; }
if (fclose(fp) != 0) { puts("Close failed"); return 1; }
fp = fopen("codebhavya_binary_demo.bin", "rb");
if (fp == NULL) { puts("Open failed"); return 1; }
if (fread(output, sizeof output[0], 3, fp) != 3) { fclose(fp); puts("Read failed"); return 1; }
if (fclose(fp) != 0) { puts("Close failed"); return 1; }
for (int i = 0; i < 3; ++i) { printf("%d\n", output[i]); }
return 0;
}The example uses values in the code.
10
20
30