💻 Unit 5 – Part B (Descriptive Q&A)

Programming in C

⬅ Back to Unit 5

Ad Space

Part B: Files and Preprocessor Directives

73. i. Discuss read/write of binary and text files with an example.

Text Files:

Binary Files:

Example (Writing/Reading a structure in Binary Mode):


#include <stdio.h>

struct Student {
    int roll;
    char name[50];
};

int main() {
    FILE *fp;
    struct Student s_write = {101, "Alice"};
    struct Student s_read;

    // --- Write to binary file ---
    fp = fopen("student.dat", "wb"); // "wb" = write binary
    if (fp == NULL) {
        printf("Error opening file for writing.\n");
        return 1;
    }
    fwrite(&s_write, sizeof(struct Student), 1, fp);
    fclose(fp);
    printf("Wrote: %d, %s\n", s_write.roll, s_write.name);

    // --- Read from binary file ---
    fp = fopen("student.dat", "rb"); // "rb" = read binary
    if (fp == NULL) {
        printf("Error opening file for reading.\n");
        return 1;
    }
    fread(&s_read, sizeof(struct Student), 1, fp);
    fclose(fp);

    printf("Read: %d, %s\n", s_read.roll, s_read.name);

    return 0;
}

73. ii. & 77. Discuss about file processing types.

(These questions are identical).

There are two main types of file processing (or file access) in C:

  1. Sequential Access:
    • This is the default mode for files. Data is accessed in a linear sequence, one byte after another, from the beginning to the end.
    • It's like reading a book or listening to a cassette tape. To read the 100th record, you must first pass over the 99 preceding records.
    • All standard I/O functions like fgetc(), fputc(), fscanf(), and fprintf() use sequential access.
  2. Random Access (or Direct Access):
    • This mode allows you to jump to any specific byte position within a file without reading the preceding data.
    • It's like accessing a specific track on a CD or a specific byte on a hard drive.
    • This is achieved using file-positioning functions:
      • fseek(): To move the file pointer to a specific location.
      • ftell(): To get the current position of the file pointer.
      • rewind(): To reset the file pointer to the beginning.
    • This is very efficient for large data files where you need to quickly access, read, or modify specific records.

74. i. & 75., 78. ii., 79. Explain the types of file handling operations / various file operations / Read and Write operation...

(These questions are all related to basic file operations. This is a comprehensive answer.)

File handling in C involves several key operations to interact with files on the disk:

  1. Opening a File (fopen()):
    • Before any operation, a file must be "opened". This connects the program to the file.
    • FILE *fp = fopen("filename.txt", "mode");
    • The mode specifies the operation:
      • "r": Read (file must exist).
      • "w": Write (creates new file or truncates existing).
      • "a": Append (adds to the end of the file; creates if not exist).
      • "r+": Read and Write (file must exist).
      • "w+": Read and Write (creates new or truncates).
      • "a+": Read and Append (creates if not exist).
      • Add "b" for binary mode (e.g., "rb", "wb").
  2. Reading from a File:
    • fscanf(fp, "...", ...): Reads formatted data (like scanf).
    • fgetc(fp): Reads a single character.
    • fgets(buffer, size, fp): Reads a line (string).
    • fread(buffer, size, count, fp): Reads count blocks of size bytes (for binary files).
  3. Writing to a File:
    • fprintf(fp, "...", ...): Writes formatted data (like printf).
    • fputc(char, fp): Writes a single character.
    • fputs(buffer, fp): Writes a string.
    • fwrite(buffer, size, count, fp): Writes count blocks of size bytes (for binary files).
  4. Closing a File (fclose()):
    • This disconnects the program from the file and saves any buffered data.
    • fclose(fp);
    • This is crucial to prevent data loss.

Example (Write then Read):


#include <stdio.h>
int main() {
    FILE *fp;
    char text[100];

    // 1. Write to file
    fp = fopen("data.txt", "w");
    if (fp == NULL) return 1;
    fprintf(fp, "Hello World\n%d", 2025);
    fclose(fp);

    // 2. Read from file
    fp = fopen("data.txt", "r");
    if (fp == NULL) return 1;
    fscanf(fp, "%s", text);
    printf("Read string: %s\n", text);
    int year;
    fscanf(fp, "%d", &year);
    printf("Read integer: %d\n", year);
    fclose(fp);

    return 0;
}

74. ii. Write a C program to copy the contents of one file to another.


#include <stdio.h>
#include <stdlib.h> // For exit()

int main() {
    FILE *sourceFile, *destFile;
    char ch;

    // Open the source file in read mode
    sourceFile = fopen("source.txt", "r");
    if (sourceFile == NULL) {
        printf("Error: Cannot open source file.\n");
        exit(1);
    }

    // Open the destination file in write mode
    destFile = fopen("destination.txt", "w");
    if (destFile == NULL) {
        printf("Error: Cannot open destination file.\n");
        fclose(sourceFile);
        exit(1);
    }

    // Read character by character from source
    // and write to destination until EOF is reached.
    while ((ch = fgetc(sourceFile)) != EOF) {
        fputc(ch, destFile);
    }

    printf("File copied successfully!\n");

    // Close both files
    fclose(sourceFile);
    fclose(destFile);

    return 0;
}

76. Explain random access in files along with the functions used...

Random access (or direct access) allows a program to read or write data from any location in a file, without having to read through all the preceding data. This is essential for applications like databases. This is achieved using file-positioning functions:

Example (Reading 5th character, then 2nd from end):


#include <stdio.h>

int main() {
    FILE *fp;
    fp = fopen("data.txt", "w");
    fprintf(fp, "0123456789");
    fclose(fp);

    fp = fopen("data.txt", "r");
    if (fp == NULL) return 1;

    // Go to the 5th character (index 4)
    fseek(fp, 4, SEEK_SET);
    printf("5th char is: %c\n", fgetc(fp)); // Output: 4

    // Go to the 2nd to last character
    fseek(fp, -2, SEEK_END);
    printf("2nd to last char is: %c\n", fgetc(fp)); // Output: 8
    
    // Get current position
    printf("Current position: %ld\n", ftell(fp)); // Output: 9

    // Go back to start
    rewind(fp);
    printf("First char is: %c\n", fgetc(fp)); // Output: 0

    fclose(fp);
    return 0;
}

78. i. Discuss about the command line argument with an example.

Command-line arguments are parameters passed to a program when it is executed from the terminal. This allows users to provide input or specify options to the program at startup.

In C, these arguments are accessed through the parameters of the main() function:

int main(int argc, char *argv[])

Example (Program that prints its arguments):


#include <stdio.h>

// Save as "args.c", compile as "gcc args.c -o myprogram"
// Run as: ./myprogram hello world 123

int main(int argc, char *argv[]) {
    int i;

    printf("Program name: %s\n", argv[0]);
    printf("Number of arguments (argc): %d\n", argc);

    if (argc > 1) {
        printf("Arguments passed:\n");
        for (i = 1; i < argc; i++) {
            printf("  argv[%d] = %s\n", i, argv[i]);
        }
    } else {
        printf("No arguments were passed.\n");
    }

    return 0;
}

Output (when run as ./myprogram hello world 123):

Program name: ./myprogram
Number of arguments (argc): 4
Arguments passed:
  argv[1] = hello
  argv[2] = world
  argv[3] = 123

80. Compare sequential access with Random access file with an example

Here is a comparison of sequential and random file access methods:

Sequential Access:

Random Access:

Ad Space