C fwrite

Created By: chatGPT

C's fwrite function is used to write a block of data to a file. This function is defined in the standard library and is particularly useful for writing binary data, as it allows you to write multiple elements of a certain data type in a single function call. Here’s how you can use fwrite:
#include <stdio.h>

int main() {
    FILE *file;
    int numbers[] = {1, 2, 3, 4, 5};
    size_t num_elements = sizeof(numbers) / sizeof(numbers[0]);

    file = fopen("numbers.bin", "wb"); // Open a file in binary write mode
    if (file == NULL) {
        perror("Error opening file");
        return -1;
    }

    // Write the array to the file
    size_t written = fwrite(numbers, sizeof(int), num_elements, file);
    if (written != num_elements) {
        perror("Error writing data to file");
    }

    fclose(file); // Close the file
    return 0;
}

In the example above:

  • We include the stdio.h header, which is necessary for file handling functions.
  • We define an integer array with some numbers.
  • We open a file named numbers.bin in binary write mode using fopen. It's important to check if the file was opened correctly.
  • We call fwrite, passing in the array, the size of each element, the number of elements, and the file pointer.
  • Finally, we close the file with fclose to ensure that all data is written and resources are freed.

The fwrite function parameters are as follows:

  • ptr: Pointer to the data you want to write.
  • size: Size in bytes of each element to write.
  • count: Number of elements to write.
  • stream: Pointer to a FILE object that identifies the stream to write to.

It's important to note that fwrite returns the number of items successfully written, which may be less than count if an error occurs. Always check the return value to ensure that data has been written successfully.

To read back the data written in the binary file, you can use the fread function as follows:
#include <stdio.h>

int main() {
    FILE *file;
    int numbers[5]; // Create an array to store the read data
    size_t num_elements = sizeof(numbers) / sizeof(numbers[0]);

    file = fopen("numbers.bin", "rb"); // Open the file in binary read mode
    if (file == NULL) {
        perror("Error opening file");
        return -1;
    }

    // Read the array from the file
    size_t read = fread(numbers, sizeof(int), num_elements, file);
    if (read != num_elements) {
        perror("Error reading data from file");
    }

    fclose(file); // Close the file

    // Print the read numbers
    for (size_t i = 0; i < read; i++) {
        printf("%d ", numbers[i]);
    }
    printf("\n");

    return 0;
}

In this snippet:

  • We open the same binary file in rb mode for reading.
  • We read the data back into the numbers array using fread.
  • We check the number of items read to handle any errors, then print the values to the standard output.
Introduction And SetupVariablesData TypesIntFloatDoubleCharVoidUnsignedSignedConstantsEnumerationsArraysStringsStructsUnionsTypedefsPointersDynamic Memory AllocationMallocCallocReallocFreeFunctionsFunction DeclarationsFunction DefinitionsFunction CallsReturn StatementInline FunctionsRecursionHeader FilesPreprocessor DirectivesControl FlowIf StatementElse StatementElse If StatementSwitch StatementCase StatementDefault CaseLoopsFor LoopWhile LoopDo While LoopBreak StatementContinue StatementGoto StatementLabelsOperatorsArithmetic OperatorsRelational OperatorsLogical OperatorsBitwise OperatorsAssignment OperatorsConditional (ternary) OperatorComma OperatorSizeof OperatorData StructuresLinked ListsStacksQueuesTreesGraphsFunction PointersCallbacksMacrosCommentsSingle Line CommentsMulti Line CommentsSyntaxSyntax ErrorsCompilation ErrorsDebuggingStandard Input OutputPrintfScanfFile HandlingFopenFcloseFreadFwriteFprintfFgetsFputsError HandlingErrnoAssertionsExit FunctionExit CodesEvent HandlingSignal HandlingInterrupts