0% found this document useful (0 votes)
14 views

C Unit 5 notes

Uploaded by

shrushti0221
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

C Unit 5 notes

Uploaded by

shrushti0221
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

UNIT 5 File handling & Pointer

Module 1: File Handling in C

1. Definition of Files

In C, files are used to store data permanently or for the purpose of


data exchange between different programs or between a program
and the user. Files in C are classified into two types:

∙Text Files: Files that store data in a human-readable format


(ASCII characters). ∙ Binary Files: Files that store data in
binary format, making them more efficient for machine
processing.

In C, files are managed using file pointers, which are created using
the FILE type. File operations like reading, writing, and closing are
carried out using various file handling functions.

2. File Opening Modes

When opening a file, you must specify the mode in which the file
is to be opened. The mode determines how the file will be
accessed (read, write, append, etc.).

Here are the common file opening modes:

∙ r: Open for reading. The file must exist.


∙ w: Open for writing. Creates a new file or truncates an
existing file to zero length. ∙ a: Open for appending. The
data is written at the end of the file.
∙ r+: Open for both reading and writing. The file must exist.
∙ w+: Open for both reading and writing. Creates a new file or
truncates an existing file. ∙ a+: Open for both reading and
appending. The data is written at the end of the file. ∙ b
(optional): Used to specify binary mode (e.g., rb, wb, r+b).

Example of Opening a File:


#include <stdio.h>

int main() {
FILE *filePtr;

// Open a file for writing


filePtr = fopen("example.txt", "w");

if (filePtr == NULL) {
printf("Error opening file!\n");
return 1;
}
// Write to file
fprintf(filePtr, "Hello, File Handling in C!\n");

// Close the file


fclose(filePtr);

return 0;
}
3. Standard File Handling Functions

Here are some commonly used


functions for file handling: ∙
fopen(): Opens a file with a
specified mode.
Syntax:
FILE *fopen(const char *filename, const char *mode);

∙ fclose(): Closes an open file.

Syntax:
int fclose(FILE *filePtr);

∙ fread(): Reads binary data from a file.

Syntax:
size_t fread(void *ptr, size_t size,
size_t count, FILE *filePtr); ∙ fwrite():
Writes binary data to a file.
Syntax:
size_t fwrite(const void *ptr, size_t size,
size_t count, FILE *filePtr); ∙ fscanf(): Reads
formatted input from a file.
Syntax:
int fscanf(FILE *filePtr, const char *format, ...);

∙ fprintf(): Writes formatted output to a file.

Syntax:
int fprintf(FILE *filePtr, const char *format, ...);

∙ feof(): Checks if the end of a file is reached.

Syntax:
int feof(FILE *filePtr);

∙ fseek(): Moves the file pointer to a specific location in a file.

Syntax:
int fseek(FILE *filePtr, long int offset, int origin);
∙ ftell(): Returns the current file pointer position.

Syntax:
long int ftell(FILE *filePtr);

∙ rewind(): Resets the file pointer to the beginning of the file.

Syntax:
void rewind(FILE *filePtr);
4. Random Access to Files

Random access allows you to move the file pointer to any position
within a file for reading or writing. This is done using fseek() and
ftell().

∙ fseek(): Moves the file pointer to a specified position.


∙ ftell(): Returns the current position of the file pointer.

Example:
#include <stdio.h>

int main() {
FILE *filePtr;
char ch;

// Open a file for reading


filePtr = fopen("example.txt", "r");

if (filePtr == NULL) {
printf("File not found!\n");
return 1;
}

// Move to the 10th byte of the file


fseek(filePtr, 10, SEEK_SET);
ch = fgetc(filePtr); // Read the character at that position

printf("Character at position 10: %c\n", ch);

fclose(filePtr);
return 0;
}

5. Command Line Arguments

Command-line arguments are arguments passed to the program


when it is executed from the command line. The arguments are
passed to the main() function as parameters.

∙ argc: Number of command-line arguments.


∙ argv[]: Array of strings containing the arguments.

Example:
#include <stdio.h>

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


printf("Number of arguments: %d\n", argc);
for (int i = 0; i < argc; i++) {
printf("Argument %d: %s\n", i, argv[i]);
}
return 0;
}
Module 2: Pointers in C

1. Pointer Declaration

A pointer is a variable that stores the memory address of another


variable. To declare a pointer, use the * operator.

Syntax:
dataType *pointerName;

Example:
int *ptr; // Pointer to an integer

2. Pointer Initialization

A pointer can be initialized by assigning it the address of a


variable using the address-of operator (&).

Example:
int num = 10;
int *ptr = &num; // Pointer 'ptr' holds the address of 'num'

3. Pointer Arithmetic

Pointers support arithmetic operations such as addition,


subtraction, and comparison. Pointer arithmetic allows you to
traverse through arrays and memory.

∙Increment (ptr++): Moves the pointer to the next memory


location of the same type. ∙ Decrement (ptr--): Moves the
pointer to the previous memory location. ∙ Pointer
addition/subtraction: You can add or subtract integers
to/from pointers.

Example:
int arr[] = {10, 20, 30, 40};
int *ptr = arr; // Points to the first element of the array
printf("%d\n", *ptr); // Outputs 10
ptr++; // Moves to the next element
printf("%d\n", *ptr); // Outputs 20

4. Pointer to Pointer

A pointer to pointer is a pointer that stores the address of another


pointer. This is useful for dynamically allocating memory and for
dealing with multi-dimensional arrays.

Example:
int num = 10;
int *ptr1 = &num;
int **ptr2 = &ptr1; // Pointer to pointer

printf("%d\n", **ptr2); // Outputs 10


5. Arrays and Pointers

Arrays and pointers are closely related in C. An array name is


actually a constant pointer to its first element. You can use pointer
arithmetic to access array elements.

Example:
int arr[] = {10, 20, 30};
int *ptr = arr;

printf("%d\n", *(ptr + 1)); // Accesses the second element (20)

6. Functions and Pointers

Pointers can be passed to functions to modify data or for dynamic


memory allocation.

∙Passing pointers to functions allows you to modify the


data passed to the function. ∙ Returning pointers from
functions allows you to return a reference to a variable
or dynamically allocated memory.

Example of passing pointers to functions:


void increment(int *ptr) {
(*ptr)++;
}

int main() {
int num = 5;
increment(&num);
printf("%d\n", num); // Outputs 6
return 0;
}
Example of returning pointers from functions:
int* getPointer() {
static int num = 10; // static to ensure the variable
exists outside the function return &num;
}

int main() {
int *ptr = getPointer();
printf("%d\n", *ptr); // Outputs 10
return 0;
}

7. Dynamic Memory Allocation

In C, you can dynamically allocate memory during runtime using


functions from the stdlib.h library:

∙ malloc(): Allocates a block of memory of specified size.


void *malloc(size_t size);

∙ calloc(): Allocates memory for an array of elements,


initializing all bytes to zero. void *calloc(size_t num,
size_t size);
∙ realloc(): Changes the size of a previously
allocated block of memory. void *realloc(void
*ptr, size_t size);

∙ free(): Frees a previously allocated block of memory.


void free(void *ptr);

Example:
int *arr = (int *)malloc(5 * sizeof(int)); // Allocates memory for 5
integers

for (int i = 0; i < 5; i++) {


arr[i] = i + 1; // Initializing the array
}
free(arr); // Freeing allocated memory

You might also like