Computer ScienceNEB 2081

Write a C program that uses structures to represent details of five books (title, author, publisher and price) and prints them out. [8] OR Discuss the concept of binary file handling in C…

8

Write a C program that uses structures to represent details of five books (title, author, publisher and price) and prints them out. [8] OR Discuss the concept of binary file handling in C programming and explain how putw( ) and getw( ) functions facilitate binary input/output operations. Give examples. [8]

Answer

Model Answer for NEB Class 12 Computer Science (Comp) – 2081

Question: Write a C program that uses structures to represent details of five books (title, author, publisher, and price) and prints them out.


Solution: C Program Using Structures for Book Details

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

// Define a structure to store book details
struct Book {
    char title[50];
    char author[50];
    char publisher[50];
    float price;
};

int main() {
    // Declare an array of 5 Book structures
    struct Book books[5];

    // Input details for 5 books
    for (int i = 0; i < 5; i++) {
        printf("\nEnter details for Book %d:\n", i + 1);

        printf("Title: ");
        fgets(books[i].title, 50, stdin);
        books[i].title[strcspn(books[i].title, "\n")] = '\0'; // Remove newline

        printf("Author: ");
        fgets(books[i].author, 50, stdin);
        books[i].author[strcspn(books[i].author, "\n")] = '\0';

        printf("Publisher: ");
        fgets(books[i].publisher, 50, stdin);
        books[i].publisher[strcspn(books[i].publisher, "\n")] = '\0';

        printf("Price: ");
        scanf("%f", &books[i].price);
        while (getchar() != '\n'); // Clear input buffer
    }

    // Print the details of all books
    printf("\n--- Book Details ---\n");
    for (int i = 0; i < 5; i++) {
        printf("\nBook %d:\n", i + 1);
        printf("Title: %s\n", books[i].title);
        printf("Author: %s\n", books[i].author);
        printf("Publisher: %s\n", books[i].publisher);
        printf("Price: %.2f\n", books[i].price);
    }

    return 0;
}

Explanation:

  1. Structure Definition (struct Book):

    • A structure named Book is defined with four members:
      • title (string, 50 chars max)
      • author (string, 50 chars max)
      • publisher (string, 50 chars max)
      • price (float)
  2. Array of Structures (books[5]):

    • An array of 5 Book structures is declared to store details of 5 books.
  3. Input Loop (for loop):

    • The program prompts the user to enter details for each book (title, author, publisher, price).
    • fgets() is used to read strings safely (avoiding buffer overflow).
    • strcspn() removes the trailing newline character from string inputs.
    • scanf() reads the price (float), and while (getchar() != '\n') clears the input buffer to prevent issues in subsequent fgets() calls.
  4. Output Loop (for loop):

    • The program prints the details of all 5 books in a structured format.

Sample Input & Output:

Input:

Enter details for Book 1:
Title: C Programming
Author: Dennis Ritchie
Publisher: Pearson
Price: 450.50

Enter details for Book 2:
Title: Data Structures
Author: Horowitz
Publisher: Wiley
Price: 650.75
...

Output:

--- Book Details ---

Book 1:
Title: C Programming
Author: Dennis Ritchie
Publisher: Pearson
Price: 450.50

Book 2:
Title: Data Structures
Author: Horowitz
Publisher: Wiley
Price: 650.75
...

Key Points:

  • Structures group related data (title, author, publisher, price) into a single unit.
  • Arrays of structures allow storing multiple records efficiently.
  • fgets() and strcspn() ensure safe string input handling.
  • Buffer clearing (while (getchar() != '\n')) prevents input mixing issues between scanf() and fgets().

OR


Model Answer for NEB Class 12 Computer Science (Comp) – 2081

Question: Discuss the concept of binary file handling in C programming and explain how putw() and getw() functions facilitate binary input/output operations. Give examples.


Binary File Handling in C

Binary file handling involves reading from and writing to files in their original binary format (unlike text files, where data is converted to ASCII/Unicode). This method is faster and preserves data integrity (e.g., integers, floats, structures) exactly as stored in memory.


Key Features of Binary Files:

Feature Binary Files Text Files
Data Representation Stores data in raw binary format. Converts data to ASCII/Unicode.
Speed Faster I/O operations. Slower due to conversion overhead.
Storage Efficiency Compact (no extra characters). Less efficient (e.g., \n for lines).
Data Types Supports all C data types (int, float, struct, etc.). Limited to characters/strings.
Use Cases Databases, images, audio, serialized objects. Logs, configuration files, text documents.

Binary File Modes in C:

Mode Description
"rb" Open for reading in binary mode.
"wb" Open for writing in binary mode (creates/truncates file).
"ab" Open for appending in binary mode.
"rb+" Open for reading and writing in binary mode.
"wb+" Open for writing and reading in binary mode (creates/truncates file).

putw() and getw() Functions

These functions are used for binary I/O of integers (specifically int type). They are deprecated in modern C (replaced by fwrite() and fread()), but still relevant for understanding binary operations.

  1. int putw(int value, FILE *stream)

    • Writes an integer (value) to a binary file (stream).
    • Returns the integer written on success, EOF on failure.
  2. int getw(FILE *stream)

    • Reads an integer from a binary file (stream).
    • Returns the integer read on success, EOF on failure.

Example: Binary File Handling with putw() and getw()

#include <stdio.h>

int main() {
    FILE *file;
    int numbers[5] = {10, 20, 30, 40, 50};
    int num;

    // Write integers to a binary file
    file = fopen("data.bin", "wb");
    if (file == NULL) {
        printf("Error opening file!\n");
        return 1;
    }

    for (int i = 0; i < 5; i++) {
        putw(numbers[i], file); // Write each integer in binary
    }
    fclose(file);

    // Read integers from the binary file
    file = fopen("data.bin", "rb");
    if (file == NULL) {
        printf("Error opening file!\n");
        return 1;
    }

    printf("Reading from binary file:\n");
    for (int i = 0; i < 5; i++) {
        num = getw(file); // Read each integer
        printf("%d ", num);
    }
    fclose(file);

    return 0;
}

Output:

Reading from binary file:
10 20 30 40 50

Explanation of the Example:

  1. Writing to Binary File ("wb" mode):

    • The program opens data.bin in binary write mode.
    • putw() writes each integer from the array numbers directly in binary format.
  2. Reading from Binary File ("rb" mode):

    • The file is reopened in binary read mode.
    • getw() reads integers exactly as stored, preserving their binary representation.
  3. Advantages Over Text Files:

    • No data loss (e.g., floating-point numbers are stored precisely).
    • Faster processing for large datasets (e.g., databases, multimedia files).

Modern Alternatives to putw()/getw()

For better portability and flexibility, use:

  • fwrite() and fread() for writing/reading arbitrary data types (e.g., structures).
  • fprintf()/fscanf() for formatted binary data (less common but useful for specific cases).

Example with fwrite() and fread():

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

int main() {
    FILE *file;
    struct Student s1 = {1, "Rama", 95.5};

    // Write structure to binary file
    file = fopen("student.bin", "wb");
    fwrite(&s1, sizeof(s1), 1, file);
    fclose(file);

    // Read structure from binary file
    file = fopen("student.bin", "rb");
    fread(&s1, sizeof(s1), 1, file);
    printf("Roll: %d, Name: %s, Marks: %.2f\n", s1.roll, s1.name, s1.marks);
    fclose(file);

    return 0;
}

Output:

Roll: 1, Name: Rama, Marks: 95.50

Key Takeaways:

  • Binary files preserve data exactly as stored in memory.
  • putw() and getw() are legacy functions for integer binary I/O.
  • Modern C prefers fwrite()/fread() for general binary operations.
  • Binary files are essential for performance-critical applications (e.g., databases, games).

Discussion

Loading…

More Computer Science questions

All Computer Science old questions