C Enums

C Enums:

Enumerations (enums) in C are a user-defined data type that consists of integral constants. They are used to create a set of named integer values. Enums provide a way to make your code more readable and maintainable by giving meaningful names to numeric values. Here's how you can define and use enums in C:

        
#include <stdio.h>

// Define an enumeration for days of the week
enum Days {
    Sunday,    // 0
    Monday,    // 1
    Tuesday,   // 2
    Wednesday, // 3
    Thursday,  // 4
    Friday,    // 5
    Saturday   // 6
};

int main() {
    // Declare a variable of the enum type
    enum Days today;

    // Assign a value from the enum
    today = Wednesday;

    // Use the enum value in a switch statement
    switch (today) {
        case Sunday:
            printf("It's Sunday!\n");
            break;
        case Wednesday:
            printf("It's Wednesday!\n");
            break;
        default:
            printf("It's not Sunday or Wednesday.\n");
    }

    return 0;
}
        
    

In this example, we defined an enum Days with named constants for each day of the week. We assigned a value from the enum to the today variable and used a switch statement to determine the day.

File Handling in C:

C provides file handling functions for reading from and writing to files. The two primary modes for file handling are text mode and binary mode. Let's cover some of the essential file handling functions and concepts with examples:

        
#include <stdio.h>

int main() {
    FILE *file;

    // Opening a file in write mode
    file = fopen("example.txt", "w");

    if (file == NULL) {
        printf("File cannot be opened.\n");
        return 1;
    }

    // Write data to the file
    fprintf(file, "Hello, world!\n");

    // Close the file
    fclose(file);

    return 0;
}
        
    

In this example, we opened a file named "example.txt" in write mode using fopen(), wrote some data to it with fprintf(), and closed the file using fclose().

        
#include <stdio.h>

int main() {
    FILE *file;
    char data[100];

    file = fopen("example.txt", "r");

    if (file == NULL) {
        printf("File cannot be opened.\n");
        return 1;
    }

    // Read data from the file
    fscanf(file, "%s", data);

    // Close the file
    fclose(file);

    printf("Data from the file: %s\n", data);

    return 0;
}
        
    

In this example, we opened the same "example.txt" file in read mode, read data from it with fscanf(), and closed the file. The data is then printed to the console.

These are just basic examples to illustrate the concepts of enums and file handling in C. Real-world applications may involve more complex operations and error handling for file handling operations.

Next Topic