C fread

Created By: chatGPT

The fread function in C is used to read binary data from a file. This function is particularly useful when you need to read a large amount of binary data, such as an array or a structure. The function prototype is as follows:
size_t fread(void *ptr, size_t size, size_t count, FILE *stream);
Parameters of fread:
  1. ptr: A pointer to a block of memory where the read data should be stored.
  2. size: The size in bytes of each element to be read.
  3. count: The number of elements to be read.
  4. stream: The pointer to a FILE object that specifies an input stream.
The return value of fread is the number of elements successfully read, which may be less than count if an error or end-of-file occurs. To check for such conditions, it's important to also utilize feof and ferror functions.
Here’s an example demonstrating how to use fread to read data from a binary file into an array:
#include <stdio.h>
#include <stdlib.h>

int main() {
    FILE *file;
    int buffer[10];
    size_t result;

    // Open the file in binary mode for reading
    file = fopen("data.bin", "rb");
    if (file == NULL) {
        perror("Error opening file");
        return EXIT_FAILURE;
    }

    // Read data into buffer
    result = fread(buffer, sizeof(int), 10, file);
    if (result != 10) {
        if (feof(file)) {
            printf("Reached end of file after reading %zu elements.\n", result);
        }
        if (ferror(file)) {
            perror("Error reading file");
        }
    }

    // Close the file
    fclose(file);

    // Print the read elements
    for (size_t i = 0; i < result; i++) {
        printf("Element %zu: %d\n", i, buffer[i]);
    }

    return EXIT_SUCCESS;
}

In this example:

  • A file called data.bin is opened in binary read mode.
  • fread reads up to 10 integers into the array buffer.
  • After reading, it checks whether the read was successful and handles either end-of-file or error conditions accordingly.
  • Finally, it prints the elements of the read array.
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