Unit 5-Notes-structure-union and file handling (1)

UNIT - V STRUCTURE, UNION AND FILE HANDLING

Structure in C

  • Definition: User-defined data type used to group different types of items into a single type.

  • Declaration: The struct keyword is used for definition.

  • Members: Items in the structure, which can be of any valid data type. They are stored in contiguous memory locations.

  • Use Case: For example, instead of multiple variables for a book's title, author, price, and number of pages, a single structure can encapsulate these attributes.

C Structure Declaration Syntax
struct structure_name {
    data_type member_name1;
    data_type member_name2;
    ...
};
  • Example:

struct Person {
    char name[50];
    int citNo;
    float salary;
};
  • No memory is allocated until a variable of this structure type is defined.

Creating Structure Variables

  • Instance Creation: Define variables after the structure template.

  • Method 1:

struct structure_name variable1, variable2, ....;
  • Method 2: Declare variables after structure template:

struct Person {
    // definition
} person1, person2, p[20];
  • Accessing Members: Use . (dot operator) to access members.

Initializing Structure Members

  • Restrictions: Members cannot be initialized within the declaration.

  • Example:

struct Point {
    int x; // Not allowed to initialize here
    int y;
};
  • Default Initialization: Members not explicitly initialized have garbage values.

  • Initialization Methods:

    1. Using Assignment Operator:

str.member1 = value1;
  1. Using Initializer List:

struct structure_name str = {value1, value2, ...};
  1. Using Designated Initializer List (C99):

struct structure_name str = {.member1 = value1, ....};

Examples of Using Structures

Person Structure Implementation
#include <stdio.h>
#include <string.h>

struct Person {
    char name[50];
    int citNo;
    float salary;
} person1;

int main() {
    strcpy(person1.name, "George Orwell");
    person1.citNo = 1984;
    person1.salary = 2500;
    printf("Name: %s\n", person1.name);
    printf("Citizenship No.: %d\n", person1.citNo);
    printf("Salary: %.2f", person1.salary);
}

Output:

Name: George Orwell
Citizenship No.: 1984
Salary: 2500.00
Book Structure Implementation
#include <stdio.h>
struct book {
    char title[10];
    char author[20];
    double price;
    int pages;
};

int main() {
    struct book book1 = {"Learn C", "Dennis Ritchie", 675.50, 325};
    printf("Title: %s \n", book1.title);
    printf("Author: %s \n", book1.author);
    printf("Price: %lf\n", book1.price);
    printf("Pages: %d \n", book1.pages);
}

Output:

Title: Learn C
Author: Dennis Ritchie
Price: 675.500000
Pages: 325
Size of book struct: 48

Unions in C

  • Definition: User-defined data type that can contain elements of different types. Members share the same memory location, and only one member can store data at a time.

  • Union Declaration Syntax:

union union_name {
    datatype member1;
    datatype member2;
    ...
};
  • Example:

union car {
    char name[50];
    int price;
};
  • Access Members: Use the . operator similar to structures.

Differences Between Structures and Unions

  • Memory Allocation: Structures allocate memory for all members, while unions allocate memory only for the largest member.

  • Example Code:

#include <stdio.h>

union unionJob {
    char name[32];
    float salary;
    int workerNo;
} uJob;

struct structJob {
    char name[32];
    float salary;
    int workerNo;
} sJob;

int main() {
    printf("size of union = %d bytes\n", sizeof(uJob));
    printf("size of structure = %d bytes\n", sizeof(sJob));
}

Output:

size of union = 32
size of structure = 40

File Handling in C

  • Definition: Files are collections of data stored in secondary memory, enabling data persistence beyond program execution.

  • Importance:

    • Reusability: Easy data access, updating, and deletion anywhere, anytime.

    • Portability: Secure transfer of files without losing data.

    • Efficiency: Access large amounts of data quickly and efficiently.

    • Storage Capacity: Allows a significant amount of data storage without overloading memory.

Types of Files

  1. Text Files: Contain ASCII characters, read and written by any text editor, ending each line with '
    '. Stored typically with a .txt extension.

  2. Binary Files: Contain binary data, created and read by programs, more secure, usually with a .bin extension.

File Operations

C File Operations Include:
  1. Creation of a New File: Use fopen() with attributes like "a", "w".

  2. Opening an Existing File: Use fopen().

  3. Reading from File: Use fscanf() or fgets().

  4. Writing to a File: Use fprintf() or fputs().

  5. Moving File Pointer: Use fseek() or rewind() to position the file pointer.

  6. Closing a File: Use fclose().

File Pointer Declaration

  • Declaration Syntax: FILE *file_ptr;

  • Opening Example: file_ptr = fopen("fileName.txt", "w");

File Modes

Opening Modes

Description

r

Read existing file; NULL if not found

w

Write; overwrites existing or creates new

a

Append; data is added to existing or creates new

r+

Read and write; NULL if not found

w+

Write and read; overwrites existing or creates new

a+

Append and read; NULL if not found

Writing to a Text File Example

#include <stdio.h>
int main() {
    FILE *fp = fopen("test.txt", "w");
    for (int i = 0; i < 10; i++)
        fprintf(fp, "This is the line #%d\n", i + 1);
    fclose(fp);
    return 0;
}

Reading from a File Example

#include <stdio.h>
int main() {
    char str[80];
    FILE* ptr = fopen("Hello.txt", "r");
    if (ptr != NULL) {
        if (fgets(str, 80, ptr) != NULL)
            puts(str);
        fclose(ptr);
    }
    return 0;
}

Moving File Pointers

  1. fseek():

    • Syntax: fseek(FILE *stream, long int offset, int whence);

    • whence can be SEEK_SET, SEEK_CUR, or SEEK_END.

  2. rewind(): Resets the pointer to the start of the file.

    • Syntax: rewind(file_pointer);

Checking if a File Exists

  • Use fopen() to attempt reading. If successful, the file exists.

Removing a File

  • remove() function:

    • Syntax: int remove(const char *filename);

    • Returns 0 on success, -1 on failure.

    • Example:

    if (remove(filename) == 0)
        printf("The file was deleted.");

Additional Functions for File Operations

  • Reading:

    • fscanf(); fgets(); fgetc(); fread().

  • Writing:

    • fprintf(); fputs(); fputc(); fwrite().

  • Closing Files: Always use fclose(file_pointer); to free memory.