Pointers and File Handling
Programming in C тАУ Part 5: Pointers and File Handling
Class 12 ┬╖ Computer Science ┬╖ Unit 4: Programming in C
All programs below were compiled and run, and the outputs are real. Memory addresses (like
0x7ffe...) change on every run and every computer, so your addresses will differ.
Navigation: тЖР Part 4: Functions, Structures and Unions ┬╖ Part 5
Table of Contents
- Pointers
- Pointer Arithmetic and Arrays
- Pointers and Functions, Strings, Structures
- Dynamic Memory Allocation
- File Handling
- Writing and Reading Text Files
- Binary Files and Random Access
- Quick Revision Table
- Practice Questions
1. Pointers
A pointer is a variable that stores the memory address of another variable.
| Symbol | Name | Meaning |
|---|---|---|
&x | Address-of operator | The address of x |
*p | Indirection (dereference) operator | The value stored at the address held in p |
int *p; | Pointer declaration | p can hold the address of an int |
int x = 10;
int *p = &x; /* p holds the address of x */
*p = 20; /* changes x to 20 */
#include <stdio.h>
int main(void)
{
int age = 17;
int *p; /* p can store the address of an int */
p = &age; /* & gives the address of age */
printf("Value of age : %d\n", age);
printf("Value using *p : %d\n", *p);
printf("Value using *(&age) : %d\n", *(&age));
printf("Address of age : %p\n", (void *)&age);
printf("Address stored in p : %p\n", (void *)p);
printf("Address of p itself : %p\n", (void *)&p);
*p = 20; /* changing the value through the pointer */
printf("After *p = 20, age : %d\n", age);
return 0;
}
Output:
Value of age : 17
Value using *p : 17
Value using *(&age) : 17
Address of age : 0x7fff940b12ec
Address stored in p : 0x7fff940b12ec
Address of p itself : 0x7fff940b12f0
After *p = 20, age : 20
Advantages of pointers
- Functions can change the original variables (call by reference)
- Efficient work with arrays and strings
- Dynamic memory allocation (
malloc) - Needed for data structures such as linked lists
Pointer to pointer
#include <stdio.h>
int main(void)
{
int a = 10, *b, **c;
b = &a; /* b points to a */
c = &b; /* c points to b */
printf("Value of a using a : %d\n", a);
printf("Value of a using *b : %d\n", *b);
printf("Value of a using **c : %d\n", **c);
printf("Address of a : %p\n", (void *)&a);
printf("Address of b : %p\n", (void *)&b);
printf("Value stored in c : %p (address of b)\n", (void *)c);
return 0;
}
Output:
Value of a using a : 10
Value of a using *b : 10
Value of a using **c : 10
Address of a : 0x7ffe1c5c6c54
Address of b : 0x7ffe1c5c6c58
Value stored in c : 0x7ffe1c5c6c58 (address of b)
Common mistakes: using a pointer before giving it an address (an uninitialized pointer points anywhere), and mixing up
p(the address) with*p(the value). A pointer that points to nothing should be set toNULL.
2. Pointer Arithmetic and Arrays
Adding 1 to a pointer moves it forward by the size of its data type, not by 1 byte. So p + 1 on an int * moves 4 bytes (typically).
#include <stdio.h>
int main(void)
{
int n[] = {10, 20, 30, 40};
int *p = n; /* name of an array = address of its first element */
int i;
for (i = 0; i < 4; i++)
printf("*(p + %d) = %d address = %p\n", i, *(p + i), (void *)(p + i));
return 0;
}
Output:
*(p + 0) = 10 address = 0x7ffe8cd93ba0
*(p + 1) = 20 address = 0x7ffe8cd93ba4
*(p + 2) = 30 address = 0x7ffe8cd93ba8
*(p + 3) = 40 address = 0x7ffe8cd93bac
The array name is the address of its first element, so a[i] is the same as *(a + i).
#include <stdio.h>
int main(void)
{
int a[5] = {5, 10, 15, 20, 25};
int *p;
int sum = 0;
for (p = a; p < a + 5; p++) /* p++ moves to the next int */
sum = sum + *p;
printf("Sum using a pointer = %d\n", sum);
printf("a[2] = %d and *(a + 2) = %d\n", a[2], *(a + 2));
return 0;
}
Output:
Sum using a pointer = 75
a[2] = 15 and *(a + 2) = 15
#include <stdio.h>
int main(void)
{
int i, arr[5] = {10, 20, 30, 40, 50};
int *ptr[5]; /* array of 5 integer pointers */
for (i = 0; i < 5; i++)
ptr[i] = &arr[i];
for (i = 0; i < 5; i++)
printf("value arr[%d] = %d stored at address %p\n", i, *ptr[i], (void *)ptr[i]);
return 0;
}
Output:
value arr[0] = 10 stored at address 0x7fff8e62fad0
value arr[1] = 20 stored at address 0x7fff8e62fad4
value arr[2] = 30 stored at address 0x7fff8e62fad8
value arr[3] = 40 stored at address 0x7fff8e62fadc
value arr[4] = 50 stored at address 0x7fff8e62fae0
Array vs pointer
| Basis | Array | Pointer |
|---|---|---|
| Stores | Many values of the same type | One address |
| Name | A fixed address that cannot be changed (a++ is illegal) | A variable that can be changed (p++ is legal) |
| Memory | Allocated when declared; size fixed | Allocated separately; can point anywhere or use malloc |
sizeof | Size of the whole array | Size of the pointer only (e.g. 8 bytes) |
| Declaration | int a[5]; | int *p; |
3. Pointers and Functions, Strings, Structures
Pointers in functions
#include <stdio.h>
int add(int *x, int *y);
int main(void)
{
int a, b, c;
printf("Enter two numbers: ");
scanf("%d %d", &a, &b);
c = add(&a, &b); /* addresses are passed */
printf("Sum of %d and %d is %d\n", a, b, c);
return 0;
}
int add(int *x, int *y)
{
return *x + *y;
}
Sample run:
Enter two numbers: 8 12
Sum of 8 and 12 is 20
Pointers and strings
#include <stdio.h>
int main(void)
{
char *s = "Nepal"; /* pointer to a string constant */
char *p = s;
int length = 0;
while (*p != '\0') { /* stop at the null character */
putchar(*p);
putchar(' ');
p++;
length++;
}
printf("\nLength = %d\n", length);
return 0;
}
Output:
N e p a l
Length = 5
Pointer to a structure
With a pointer, a member is reached using the arrow operator ->. p->roll means (*p).roll.
#include <stdio.h>
struct student {
int roll;
char name[20];
float marks;
};
int main(void)
{
struct student s = {1, "Gita", 88.5f};
struct student *p = &s;
printf("Using dot : %d %s %.1f\n", s.roll, s.name, s.marks);
printf("Using -> : %d %s %.1f\n", p->roll, p->name, p->marks);
printf("Using (*p). : %d %s %.1f\n", (*p).roll, (*p).name, (*p).marks);
return 0;
}
Output:
Using dot : 1 Gita 88.5
Using -> : 1 Gita 88.5
Using (*p). : 1 Gita 88.5
Structure vs pointer
| Basis | Structure | Pointer |
|---|---|---|
| Stores | A group of values of different types | A memory address |
| Keyword / symbol | struct | * |
| Access | . operator | * or -> |
| Size | Sum of the members | Fixed (e.g. 8 bytes) |
4. Dynamic Memory Allocation
Static allocation fixes memory at compile time (int a[100];). Dynamic allocation requests memory while the program runs, in the exact size needed. These functions are in stdlib.h.
| Function | Purpose |
|---|---|
malloc(size) | Allocates size bytes (contents not set) |
calloc(n, size) | Allocates n blocks and sets them to 0 |
realloc(p, size) | Changes the size of an allocated block |
free(p) | Releases the memory |
Always check that the result is not NULL, and always free() memory after use.
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int *arr, n, i, sum = 0;
printf("How many numbers? ");
scanf("%d", &n);
arr = (int *)malloc(n * sizeof(int)); /* memory is created at run time */
if (arr == NULL) {
printf("Not enough memory\n");
return 1;
}
printf("Enter %d numbers: ", n);
for (i = 0; i < n; i++) {
scanf("%d", &arr[i]);
sum = sum + arr[i];
}
printf("Sum = %d, Average = %.2f\n", sum, (float)sum / n);
free(arr); /* give the memory back */
return 0;
}
Sample run:
How many numbers? 5
Enter 5 numbers: 12 7 9 20 2
Sum = 50, Average = 10.00
5. File Handling
A file stores data permanently on disk. Variables vanish when the program ends, but a file keeps the data.
Types of files
| Type | Stores | Opened with |
|---|---|---|
| Text file | Data as readable characters | Modes like "r", "w" |
| Binary file | Data in the same form as in memory (not readable) | Modes like "rb", "wb" |
Steps
- Declare a file pointer:
FILE *fp; - Open the file:
fp = fopen("name.txt", "mode");(it returnsNULLon failure) - Read or write
- Close:
fclose(fp);
File modes
| Mode | Meaning | If the file does not exist |
|---|---|---|
"r" | Read only | Fails (returns NULL) |
"w" | Write; erases old contents | Created |
"a" | Append (add to the end) | Created |
"r+" | Read and write | Fails |
"w+" | Read and write; erases old contents | Created |
"a+" | Read and append | Created |
Add b for binary files ("rb", "wb", "ab").
File functions
| Function | Purpose |
|---|---|
fopen() / fclose() | Open / close a file |
fprintf() / fscanf() | Write / read formatted data |
fputc() / fgetc() | Write / read one character |
fputs() / fgets() | Write / read a string (line) |
fwrite() / fread() | Write / read blocks (binary) |
fseek() / ftell() / rewind() | Move to / report / reset the position |
feof() | Tests for the end of the file |
EOF is a special value that marks the end of the file.
6. Writing and Reading Text Files
Writing with fprintf()
#include <stdio.h>
int main(void)
{
char n[20], d[20];
int a, b;
FILE *fptr;
fptr = fopen("patient.txt", "w"); /* "w" creates the file */
if (fptr == NULL) {
printf("Cannot open the file\n");
return 1;
}
printf("Enter name, disease, age and bed number: ");
scanf("%19s %19s %d %d", n, d, &a, &b);
fprintf(fptr, "%s %s %d %d\n", n, d, a, b);
fclose(fptr); /* always close the file */
printf("Record saved in patient.txt\n");
return 0;
}
Sample run:
Enter name, disease, age and bed number: Ram Fever 25 12
Record saved in patient.txt
The file patient.txt now contains:
Ram Fever 25 12
Writing several records
#include <stdio.h>
int main(void)
{
char n[20];
int c, e, ne, m, i, num;
FILE *fptr;
fptr = fopen("student.txt", "w");
if (fptr == NULL)
return 1;
printf("How many records? ");
scanf("%d", &num);
for (i = 1; i <= num; i++) {
printf("Enter name, class and 3 marks: ");
scanf("%19s %d %d %d %d", n, &c, &e, &ne, &m);
fprintf(fptr, "%s %d %d %d %d\n", n, c, e, ne, m);
}
fclose(fptr);
return 0;
}
Sample run:
How many records? 3
Enter name, class and 3 marks: Ram 12 78 82 90
Enter name, class and 3 marks: Sita 12 45 38 60
Enter name, class and 3 marks: Hari 12 85 91 88
Appending
#include <stdio.h>
int main(void)
{
char n[20], ch;
int c, e, ne, m;
FILE *fptr;
fptr = fopen("student.txt", "a"); /* "a" adds to the end of the file */
if (fptr == NULL)
return 1;
do {
printf("Enter name, class and 3 marks: ");
scanf("%19s %d %d %d %d", n, &c, &e, &ne, &m);
fprintf(fptr, "%s %d %d %d %d\n", n, c, e, ne, m);
printf("Add another record (y/n)? ");
scanf(" %c", &ch);
} while (ch == 'y' || ch == 'Y');
fclose(fptr);
return 0;
}
Sample run:
Enter name, class and 3 marks: Mina 12 66 72 80
Add another record (y/n)? y
Enter name, class and 3 marks: Kiran 12 39 50 61
Add another record (y/n)? n
Reading the whole file
#include <stdio.h>
int main(void)
{
char n[20];
int c, e, ne, m;
float p;
FILE *fptr;
fptr = fopen("student.txt", "r"); /* "r" opens an existing file */
if (fptr == NULL) {
printf("The file does not exist\n");
return 1;
}
printf("%-10s %5s %s\n", "Name", "Class", "Percentage");
while (fscanf(fptr, "%19s %d %d %d %d", n, &c, &e, &ne, &m) != EOF) {
p = (e + ne + m) / 3.0f; /* 3.0 keeps the decimal part */
printf("%-10s %5d %10.2f\n", n, c, p);
}
fclose(fptr);
return 0;
}
Output:
Name Class Percentage
Ram 12 83.33
Sita 12 47.67
Hari 12 88.00
Mina 12 72.67
Kiran 12 50.00
Reading and filtering records
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main(void)
{
char n[20], lower[20];
int c, e, ne, m, i;
float p;
FILE *fptr;
fptr = fopen("student.txt", "r");
if (fptr == NULL) {
printf("The file does not exist\n");
return 1;
}
printf("1. Passed in all subjects (40 or more in each):\n");
while (fscanf(fptr, "%19s %d %d %d %d", n, &c, &e, &ne, &m) != EOF) {
if (e >= 40 && ne >= 40 && m >= 40)
printf(" %s %d %d %d %d\n", n, c, e, ne, m);
}
rewind(fptr); /* go back to the start of the file */
printf("2. Failed in at least one subject:\n");
while (fscanf(fptr, "%19s %d %d %d %d", n, &c, &e, &ne, &m) != EOF) {
if (e < 40 || ne < 40 || m < 40)
printf(" %s %d %d %d %d\n", n, c, e, ne, m);
}
rewind(fptr);
printf("3. Distinction (average 80 or more):\n");
while (fscanf(fptr, "%19s %d %d %d %d", n, &c, &e, &ne, &m) != EOF) {
p = (e + ne + m) / 3.0f;
if (p >= 80)
printf(" %s %d %d %d %d\n", n, c, e, ne, m);
}
rewind(fptr);
printf("4. Records of Ram (any letter case):\n");
while (fscanf(fptr, "%19s %d %d %d %d", n, &c, &e, &ne, &m) != EOF) {
for (i = 0; n[i] != '\0'; i++)
lower[i] = tolower(n[i]);
lower[i] = '\0';
if (strcmp(lower, "ram") == 0)
printf(" %s %d %d %d %d\n", n, c, e, ne, m);
}
fclose(fptr);
return 0;
}
Output:
1. Passed in all subjects (40 or more in each):
Ram 12 78 82 90
Hari 12 85 91 88
Mina 12 66 72 80
2. Failed in at least one subject:
Sita 12 45 38 60
Kiran 12 39 50 61
3. Distinction (average 80 or more):
Ram 12 78 82 90
Hari 12 85 91 88
4. Records of Ram (any letter case):
Ram 12 78 82 90
Character by character
#include <stdio.h>
int main(void)
{
FILE *f;
int ch; /* int, because EOF is an int value */
f = fopen("store.txt", "w");
if (f == NULL)
return 1;
printf("Type a line of text: ");
while ((ch = getchar()) != '\n')
fputc(ch, f); /* store one character at a time */
fclose(f);
f = fopen("store.txt", "r");
if (f == NULL)
return 1;
printf("The file contains : ");
while ((ch = fgetc(f)) != EOF) /* read one character at a time */
putchar(ch);
printf("\n");
fclose(f);
return 0;
}
Sample run:
Type a line of text: Nepal is a beautiful country
The file contains : Nepal is a beautiful country
fprintf() with a table
#include <stdio.h>
int main(void)
{
FILE *f;
int i, rn, n;
char name[25], add[35];
f = fopen("ratna.txt", "w");
if (f == NULL)
return 1;
printf("How many records? ");
scanf("%d", &n);
printf("Enter %d student roll number, name and address:\n", n);
for (i = 0; i < n; i++) {
scanf("%d %24s %34s", &rn, name, add);
fprintf(f, "%d\t%s\t%s\n", rn, name, add);
}
fclose(f);
printf("\nThe %d data records are:\n", n);
f = fopen("ratna.txt", "r");
if (f == NULL)
return 1;
while (fscanf(f, "%d %24s %34s", &rn, name, add) != EOF)
printf("%d\t%s\t%s\n", rn, name, add);
fclose(f);
return 0;
}
Sample run:
How many records? 3
Enter 3 student roll number, name and address:
1 Ram Pokhara
2 Sita Butwal
3 Hari Chitwan
The 3 data records are:
1 Ram Pokhara
2 Sita Butwal
3 Hari Chitwan
Writing lines with fputs()
#include <stdio.h>
int main(void)
{
char line[100];
FILE *f;
f = fopen("senten.txt", "w");
if (f == NULL)
return 1;
printf("Enter lines of text (press Enter on an empty line to stop):\n");
while (fgets(line, sizeof line, stdin) != NULL && line[0] != '\n')
fputs(line, f); /* store the line in the file */
fclose(f);
f = fopen("senten.txt", "r");
if (f == NULL)
return 1;
printf("\nContents of the file:\n");
while (fgets(line, sizeof line, f) != NULL)
printf("%s", line);
fclose(f);
return 0;
}
Sample run:
Enter lines of text (press Enter on an empty line to stop):
C is powerful
Files store data permanently
Contents of the file:
C is powerful
Files store data permanently
Reading numbers from a file
#include <stdio.h>
int main(void)
{
int ag, n, i, sum = 0;
float avg;
FILE *f;
f = fopen("age.txt", "w");
if (f == NULL)
return 1;
printf("How many students? ");
scanf("%d", &n);
for (i = 1; i <= n; i++) {
printf("Enter age of student %d: ", i);
scanf("%d", &ag);
fprintf(f, "%d\n", ag);
}
fclose(f);
f = fopen("age.txt", "r");
if (f == NULL)
return 1;
for (i = 0; i < n; i++) {
fscanf(f, "%d", &ag);
sum = sum + ag;
}
fclose(f);
avg = (float)sum / n;
printf("Average age of %d students = %.2f\n", n, avg);
return 0;
}
Sample run:
How many students? 4
Enter age of student 1: 17 18 16 19
Enter age of student 2: Enter age of student 3: Enter age of student 4: Average age of 4 students = 17.50
Checking that a file exists
#include <stdio.h>
void show_file(const char *name)
{
FILE *f;
int ch;
f = fopen(name, "r");
if (f == NULL) { /* fopen returns NULL on failure */
printf("The file %s does not exist\n\n", name);
return;
}
printf("Contents of %s:\n", name);
while ((ch = fgetc(f)) != EOF)
putchar(ch);
printf("\n");
fclose(f);
}
int main(void)
{
show_file("notes.txt");
show_file("missing.txt");
return 0;
}
Output:
Contents of notes.txt:
C is a powerful language.
Files store data permanently.
The file missing.txt does not exist
Counting characters, words and lines
#include <stdio.h>
#include <ctype.h>
int main(void)
{
FILE *f;
int ch, chars = 0, words = 0, lines = 0, inword = 0;
f = fopen("notes.txt", "r");
if (f == NULL) {
printf("The file does not exist\n");
return 1;
}
while ((ch = fgetc(f)) != EOF) {
chars++;
if (ch == '\n')
lines++;
if (isspace(ch))
inword = 0;
else if (!inword) { /* a new word starts here */
inword = 1;
words++;
}
}
fclose(f);
printf("Characters = %d\nWords = %d\nLines = %d\n", chars, words, lines);
return 0;
}
Output:
Characters = 80
Words = 12
Lines = 3
fprintf() vs fscanf()
| Basis | fprintf() | fscanf() |
|---|---|---|
| Purpose | Writes formatted data to a file | Reads formatted data from a file |
| Syntax | fprintf(fp, "%d", x); | fscanf(fp, "%d", &x); |
| File mode | "w", "a" | "r" |
| Variables | Value | Address (&x) |
| Similar to | printf() | scanf() |
7. Binary Files and Random Access
fwrite() and fread() store a whole structure in one call.
fwrite(&record, sizeof(record), 1, fp); /* address, size, count, file */
fread (&record, sizeof(record), 1, fp);
#include <stdio.h>
struct student {
char name[30];
char add[30];
};
int main(void)
{
struct student s;
char next;
FILE *fp;
fp = fopen("student.dat", "wb"); /* "wb" = write in binary mode */
if (fp == NULL)
return 1;
do {
printf("Enter the name of the student: ");
scanf("%29s", s.name);
printf("Enter the address of the student: ");
scanf("%29s", s.add);
fwrite(&s, sizeof(s), 1, fp); /* write one whole structure */
printf("Do you want to write the next record (y/n)? ");
scanf(" %c", &next);
} while (next == 'y' || next == 'Y');
fclose(fp);
fp = fopen("student.dat", "rb");
if (fp == NULL)
return 1;
printf("\n%-15s %s\n", "Name", "Address");
while (fread(&s, sizeof(s), 1, fp) == 1) /* read one structure at a time */
printf("%-15s %s\n", s.name, s.add);
fclose(fp);
return 0;
}
Sample run:
Enter the name of the student: Ram
Enter the address of the student: Pokhara
Do you want to write the next record (y/n)? y
Enter the name of the student: Sita
Enter the address of the student: Butwal
Do you want to write the next record (y/n)? n
Name Address
Ram Pokhara
Sita Butwal
Sequential vs random access
| Basis | Sequential access | Random access |
|---|---|---|
| Reading order | From the beginning, record by record | Directly to any position |
| Functions | fgetc(), fscanf(), fgets() | fseek(), ftell(), rewind() |
| Speed for a record in the middle | Slow (must pass all before it) | Fast |
fseek(fp, offset, origin) moves the position. The origin is SEEK_SET (start), SEEK_CUR (current) or SEEK_END (end).
#include <stdio.h>
int main(void)
{
FILE *f;
int ch;
f = fopen("alpha.txt", "r");
if (f == NULL)
return 1;
fseek(f, 3, SEEK_SET); /* 3 bytes from the beginning */
ch = fgetc(f);
printf("Character at position 3 : %c\n", ch);
printf("Current position : %ld\n", ftell(f));
fseek(f, 2, SEEK_CUR); /* 2 bytes forward from here */
ch = fgetc(f);
printf("Two characters ahead : %c\n", ch);
rewind(f); /* back to the beginning */
ch = fgetc(f);
printf("After rewind() : %c\n", ch);
fseek(f, 0, SEEK_END); /* jump to the end */
printf("File size : %ld bytes\n", ftell(f));
fclose(f);
return 0;
}
Output:
Character at position 3 : D
Current position : 4
Two characters ahead : G
After rewind() : A
File size : 11 bytes
Correction:
lseek()seen in some notes is a low-level system call, not a standard I/O function. The standard function isfseek().
8. Quick Revision Table
| Topic | Key point |
|---|---|
| Pointer | Variable holding an address; & gives the address, * the value |
p + 1 | Moves by the size of the pointed type |
a[i] | Same as *(a + i) |
-> | Member access through a structure pointer |
malloc / free | Allocate / release memory at run time |
fopen modes | r read, w write (erases), a append |
| Always | Check for NULL, then fclose() |
fprintf / fscanf | Write / read formatted file data |
fread / fwrite | Binary block I/O |
fseek | Random access |
9. Practice Questions
Short-answer questions
- What is a pointer? Write its advantages. (NEB Q15)
- Differentiate between array and pointer. (NEB Q17)
- Differentiate between structure and pointer. (NEB Q18)
- What is dynamic memory allocation? Name the functions used.
- What is a file? List the file opening modes.
- Differentiate between sequential and random access files. (NEB Q19)
- Differentiate between
fprintf()andfscanf(). (NEB Q20)
Programming questions (exam favourites)
- Write a program that stores the name, disease, age and bed number of a patient in a file.
- Write a program to read the records back from a file and display them.
- Write a program to count the characters, words and lines of a text file.
- Write a program using a pointer to swap two numbers.
- Write a program to store and display student records using a binary file.
Navigation: тЖР Part 4: Functions, Structures and Unions ┬╖ Part 5
Prepared for NEB Class 12 Computer Science exam revision.