20CYS113-20CYS181-Computer-Programming-and-Lab

20CYS113 - Computer-Programming and 20CYS181 - Computer Programming Lab


File Handling in C

File handling in general involves operations related to reading, writing, and manipulating existing files in the filesystem. It allows the program to perform tasks such as creating files, opening files, reading contents from files, writing contents to files, and closing files.

Opening a File:

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

Closing a File:

fclose(file);

Reading from a File:

char buffer[100];
fgets(buffer, sizeof(buffer), file);

Writing to a File:

fputs("Hello, world!", file);

Reading/Writing through the file - Checking End of File (EOF)

while (!feof(file)) {
    // read or write contents
}

File Modes

Reading contents from a file (character by character)

#include <stdio.h>

int main() {
    FILE *file;         // Declare a pointer to a FILE structure
    char filename[100]; // Store the filename
    char ch;            // Store each character read from the file

    printf("Enter the filename: ");
    scanf("%s", filename);  // Read the filename from the user

    // Open the file in "r" mode (read mode)
    file = fopen(filename, "r");

    // Check if the file was opened successfully
    if (file == NULL) {
        printf("Error opening the file.\n");
        return 1;
    }

    // Read and print the file contents
    printf("File contents:\n");
    while ((ch = fgetc(file)) != EOF) {
        printf("%c", ch);  // Print each character read from the file
    }

    // Close the file
    fclose(file);

    return 0;
}

Output

fileread-op

Writing contents to the file

#include <stdio.h>

int main() {
    FILE *file;                     // Declare a pointer to a FILE structure
    char filename[100];             // Store the filename
    char content[1000];             // Store the content to be written to the file

    printf("Enter the filename: ");
    scanf("%99s", filename);        // Read the filename from the user

    // Open the file in "w" mode (write mode)
    file = fopen(filename, "w");

    // Check if the file was opened successfully
    if (file == NULL) {
        printf("Error opening the file.\n");
        return 1;
    }

    printf("Enter content to write to the file (max 1000 characters):\n");

    // Clear the input buffer
    int c;
    while ((c = getchar()) != '\n' && c != EOF);

    // Read content from the user using fgets()
    fgets(content, sizeof(content), stdin);

    // Write the content to the file using fputs()
    fputs(content, file);

    // Close the file
    fclose(file);

    printf("Content written to the file successfully.\n");

    return 0;
}

Output

filewrite-op

Posted on: 14th June, 2023 in HPOJ.

Reading contents from a file (line by line) - Example to parse ‘username’ and ‘password’

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAX_LINE_LENGTH 100

int main() {
    FILE *file;
    char line[MAX_LINE_LENGTH];

    // Open the file for reading
    file = fopen("userpass.txt", "r");
    if (file == NULL) {
        printf("Failed to open the file.\n");
        return 1;
    }

    // Read the file line by line
    while (fgets(line, MAX_LINE_LENGTH, file) != NULL) {
        // Remove the newline character at the end of the line
        // strcspn(line, "\n") finds the position of the newline character in the line string, and line[strcspn(line, "\n")] = '\0';
        // replaces the newline character with the null character to terminate the string at that point.
        line[strcspn(line, "\n")] = '\0';

        // Split the line into username and password
        // strtok() to tokenize the 'line' string based on the delimiter ":"
        char *username = strtok(line, ":");
        char *password = strtok(NULL, ":");

        // Print the parsed username and password
        printf("Username: %s\n", username);
        printf("Password: %s\n", password);
        printf("-----------------\n");
    }

    // Close the file
    fclose(file);

    return 0;
}

Input

userdata-txt

Output

line-output-parse-userdata