Computer ScienceUnit 511 min read
Structures, Pointers & Files in C: Syntax, Uses & File Handling
Unit 5 of Computer Science teaches how to use structures (user-defined data types), pointers (variables storing memory addresses), and file handling (reading/writing data to files) in C, with practical examples and NEB-style questions.
What You Will Learn
This unit covers:
- Structures: How to create and use custom data types.
- Pointers: How to store memory addresses and manipulate data indirectly.
- File Handling: How to read from and write to files in C.
1. Structures in C
What is a Structure?
A structure is a user-defined data type that groups different data types under a single name. It helps organize related data efficiently.
Syntax of Structure
struct structure_name {
data_type member1;
data_type member2;
...
};
structis a keyword.structure_nameis the name of the structure.member1,member2, etc., are variables of different data types.
Example: Define and Use a Structure
#include <stdio.h>
#include <string.h>
struct Student {
int rollNo;
char name[50];
float marks;
};
int main() {
struct Student s1;
s1.rollNo = 101;
strcpy(s1.name, "Ramesh");
s1.marks = 85.5;
printf("Roll No: %d\n", s1.rollNo);
printf("Name: %s\n", s1.name);
printf("Marks: %.2f\n", s1.marks);
return 0;
}
Output:
Roll No: 101
Name: Ramesh
Marks: 85.50
Accessing Structure Members
Use the dot (.) operator to access members:
s1.rollNo = 101; // Correct
// s1->rollNo = 101; // Wrong (-> is for pointers)
Passing Structures to Functions
You can pass structures to functions by value or by reference (using pointers).
Example: Pass by Value
void display(struct Student s) {
printf("Roll No: %d\n", s.rollNo);
printf("Name: %s\n", s.name);
}
Example: Pass by Reference (Pointer)
void display(struct Student *s) {
printf("Roll No: %d\n", s->rollNo);
printf("Name: %s\n", s->name);
}
Arrays of Structures
You can store multiple structures in an array.
struct Student students[3];
students[0].rollNo = 101;
strcpy(students[0].name, "Ramesh");
students[0].marks = 85.5;
Typedef with Structures
Use typedef to simplify structure declaration:
typedef struct {
int rollNo;
char name[50];
float marks;
} Student;
Now, you can declare variables like this:
Student s1; // Instead of struct Student s1;
2. Pointers in C
What is a Pointer?
A pointer is a variable that stores the memory address of another variable. It allows indirect access to data.
Syntax of Pointers
data_type *pointer_name;
*declares a pointer variable.pointer_nameholds the address of another variable.
Example: Basic Pointer Usage
#include <stdio.h>
int main() {
int num = 10;
int *ptr = # // ptr stores the address of num
printf("Value of num: %d\n", num);
printf("Address of num: %p\n", (void*)&num);
printf("Value of ptr: %p\n", (void*)ptr);
printf("Value pointed by ptr: %d\n", *ptr);
return 0;
}
Output:
Value of num: 10
Address of num: 0x7ffd42a1b2ac
Value of ptr: 0x7ffd42a1b2ac
Value pointed by ptr: 10
Pointer Arithmetic
Pointers can be incremented or decremented to point to the next or previous memory location.
int arr[3] = {10, 20, 30};
int *ptr = arr;
printf("%d\n", *ptr); // 10
ptr++; // Moves to next element
printf("%d\n", *ptr); // 20
Pointers and Structures
Use the arrow (->) operator to access structure members through pointers.
classDiagram
class Student {
+int rollNo
+char[] name
+float marks
}
class StudentPtr {
+Student* ptr
}
StudentPtr --> Student : points to
StudentPtr : *ptr->rollNo
StudentPtr : (*ptr).namePointer-to-structure relationship (showing access via -> and . operators)
struct Student {
int rollNo;
char name[50];
};
int main() {
struct Student s1 = {101, "Ramesh"};
struct Student *ptr = &s1;
printf("Roll No: %d\n", ptr->rollNo); // Same as (*ptr).rollNo
printf("Name: %s\n", ptr->name);
return 0;
}
Pointers to Pointers
A pointer can store the address of another pointer.
int num = 10;
int *ptr = #
int **pptr = &ptr;
printf("%d\n", **pptr); // 10
Dynamic Memory Allocation
Use malloc(), calloc(), realloc(), and free() to allocate memory dynamically.
int *ptr = (int*)malloc(5 * sizeof(int)); // Allocates memory for 5 integers
if (ptr == NULL) {
printf("Memory allocation failed!\n");
} else {
ptr[0] = 10;
ptr[1] = 20;
free(ptr); // Frees allocated memory
}
3. File Handling in C
What is File Handling?
File handling allows you to read from and write to files using C functions.
File Operations
- Opening a File: Use
fopen(). - Reading/Writing: Use
fprintf(),fscanf(),fgets(),fputs(). - Closing a File: Use
fclose().
Syntax of File Handling Functions
FILE *fptr;
fptr = fopen("filename", "mode");
"mode"can be:"r": Read"w": Write (overwrites existing file)"a": Append"r+": Read and write
Example: Writing to a File
#include <stdio.h>
int main() {
FILE *fptr;
fptr = fopen("example.txt", "w");
if (fptr == NULL) {
printf("Error opening file!\n");
} else {
fprintf(fptr, "Hello, File Handling!\n");
fprintf(fptr, "This is a test.\n");
fclose(fptr);
}
return 0;
}
Example: Reading from a File
#include <stdio.h>
int main() {
FILE *fptr;
char line[100];
fptr = fopen("example.txt", "r");
if (fptr == NULL) {
printf("Error opening file!\n");
} else {
while (fgets(line, sizeof(line), fptr) != NULL) {
printf("%s", line);
}
fclose(fptr);
}
return 0;
}
Example: Reading Character by Character
#include <stdio.h>
int main() {
FILE *fptr;
char ch;
fptr = fopen("example.txt", "r");
if (fptr == NULL) {
printf("Error opening file!\n");
} else {
while ((ch = fgetc(fptr)) != EOF) {
printf("%c", ch);
}
fclose(fptr);
}
return 0;
}
Example: Reading Line by Line
#include <stdio.h>
int main() {
FILE *fptr;
char line[100];
fptr = fopen("example.txt", "r");
if (fptr == NULL) {
printf("Error opening file!\n");
} else {
while (fgets(line, sizeof(line), fptr) != NULL) {
printf("%s", line);
}
fclose(fptr);
}
return 0;
}
Binary File Handling
Use fread() and fwrite() for binary files.
struct Student {
int rollNo;
char name[50];
};
int main() {
struct Student s1 = {101, "Ramesh"};
FILE *fptr;
fptr = fopen("students.dat", "wb"); // "wb" for binary write
if (fptr == NULL) {
printf("Error opening file!\n");
} else {
fwrite(&s1, sizeof(struct Student), 1, fptr);
fclose(fptr);
}
return 0;
}
Comparison Table: Structures vs. Arrays
| Feature | Structure | Array |
|---|---|---|
| Data Types | Can store different data types | Stores same data type |
| Declaration | struct Student s1; |
int arr[5]; |
| Access | s1.rollNo |
arr[0] |
| Flexibility | More flexible (mixed data types) | Less flexible (same data type) |
Exam Tip
Structures:
- Know how to define, declare, and access structure members.
- Practice passing structures to functions by value and reference.
- Understand
typedefwith structures.
Pointers:
- Understand pointer arithmetic and how to use
->with structures. - Know the difference between
*(dereferencing) and&(address-of). - Practice dynamic memory allocation (
malloc,calloc,free).
- Understand pointer arithmetic and how to use
File Handling:
- Remember file modes (
"r","w","a","r+"). - Know how to read/write text and binary files.
- Practice error handling (
fptr == NULL).
- Remember file modes (
NEB Board-Style Questions
Short Answer Questions
- What is the difference between
structandtypedefin C? - Explain pointer arithmetic with an example.
- Write a program to read a structure variable from the keyboard and display it on the screen.
- What are the different modes of opening a file in C? Explain each with an example.
Programming Questions
- Write a C program to store information of 5 students (roll number, name, marks) using structures. Display the information on the screen.
- Write a C program to read a text file line by line and display it on the screen.
- Write a C program to create a binary file and store 3 records of a structure variable. Then read and display the records.
True/False
- A pointer can store the address of any variable. (True/False)
- The
fopen()function returns aNULLpointer if the file cannot be opened. (True/False) - Structures can only store one data type. (True/False)
Fill in the Blanks
- The
->operator is used to access structure members through ______. - The
fclose()function is used to ______ a file. - The
malloc()function allocates memory dynamically and returns a pointer of type ______.
Solved Examples
Example 1: Structure with User Input
#include <stdio.h>
#include <string.h>
struct Student {
int rollNo;
char name[50];
float marks;
};
int main() {
struct Student s1;
printf("Enter Roll No: ");
scanf("%d", &s1.rollNo);
printf("Enter Name: ");
scanf("%s", s1.name);
printf("Enter Marks: ");
scanf("%f", &s1.marks);
printf("\nStudent Details:\n");
printf("Roll No: %d\n", s1.rollNo);
printf("Name: %s\n", s1.name);
printf("Marks: %.2f\n", s1.marks);
return 0;
}
Input:
Enter Roll No: 101
Enter Name: Ramesh
Enter Marks: 85.5
Output:
Student Details:
Roll No: 101
Name: Ramesh
Marks: 85.50
Example 2: Pointer to Structure
#include <stdio.h>
#include <string.h>
struct Student {
int rollNo;
char name[50];
};
int main() {
struct Student s1 = {101, "Ramesh"};
struct Student *ptr = &s1;
printf("Roll No: %d\n", ptr->rollNo);
printf("Name: %s\n", ptr->name);
return 0;
}
Output:
Roll No: 101
Name: Ramesh
Example 3: File Handling (Write and Read)
#include <stdio.h>
int main() {
FILE *fptr;
char ch;
// Writing to file
fptr = fopen("test.txt", "w");
if (fptr == NULL) {
printf("Error opening file!\n");
} else {
fprintf(fptr, "Hello, File Handling!\n");
fclose(fptr);
}
// Reading from file
fptr = fopen("test.txt", "r");
if (fptr == NULL) {
printf("Error opening file!\n");
} else {
while ((ch = fgetc(fptr)) != EOF) {
printf("%c", ch);
}
fclose(fptr);
}
return 0;
}
Output:
Hello, File Handling!
Based on the NEB +2 Management syllabus for Computer Science (Comp), unit 5.
Discussion
Loading…