0% found this document useful (0 votes)
46 views21 pages

Ip 345 Units

introduction to programming

Uploaded by

Narasimha Prasad
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
46 views21 pages

Ip 345 Units

introduction to programming

Uploaded by

Narasimha Prasad
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 21

UNIT III Arrays and Strings: Arrays indexing, memory model, programs with array of

integers, two dimensional arrays, Introduction to Strings.

Arrays and Strings in C: Concepts and Operations

1. Array Indexing in C

In C, an array is a collection of elements of the same data type stored in contiguous memory
locations. Each element of an array can be accessed using an index, and the indexing starts
from 0.

Example:

#include <stdio.h>
int main()
{
int arr[] = {10, 20, 30, 40, 50};
// Accessing array elements
printf("Element at index 0: %d\n", arr[0]); // Output: 10
printf("Element at index 1: %d\n", arr[1]); // Output: 20
printf("Element at index 2: %d\n", arr[2]); // Output: 30
printf("Element at index 3: %d\n", arr[3]); // Output: 40
printf("Element at index 4: %d\n", arr[4]); // Output: 50

return 0;
}

 Here, arr[0] refers to the first element of the array, arr[1] to the second, and so
on.

2. Memory Model of Arrays in C

Arrays in C are stored in contiguous memory locations, meaning that the memory addresses
for each element are next to each other. When you declare an array, say int arr[5], the C
compiler allocates 5 contiguous memory locations to store the integers.

The key points:

 The memory of an array is contiguous, and each element occupies the same amount of
memory as the data type.
 The base address of an array is the address of the first element (arr[0]).

For example, if the base address of arr[0] is 0x1000, the addresses for the other elements will
be:

 arr[0] -> 0x1000


 arr[1] -> 0x1004 (assuming each integer occupies 4 bytes)
 arr[2] -> 0x1008, and so on.

1
3. Programs with Arrays of Integers

Here’s a simple C program demonstrating the use of arrays of integers:

#include <stdio.h>

int main() {
int arr[] = {10, 20, 30, 40, 50}; // Array initialization

// Loop to print array elements


for (int i = 0; i < 5; i++) {
printf("Element at index %d: %d\n", i, arr[i]);
}

return 0;
}

In this program:

 The array arr[] is initialized with five integers.


 A for loop is used to access and print each element of the array by its index.

4. Two-Dimensional Arrays in C

A two-dimensional array can be thought of as an array of arrays, or a matrix. In C, it is


declared as type arr[rows][columns].

Example:

#include <stdio.h>
int main() {
// Declaration of a 2D array (3 rows, 4 columns)
int arr[3][4] = { {1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12} };
// Accessing elements using two indices
printf("Element at arr[0][0]: %d\n", arr[0][0]); // Output: 1
printf("Element at arr[1][2]: %d\n", arr[1][2]); // Output: 7

// Using loops to print all elements of the 2D array


printf("All elements of the 2D array:\n");
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 4; j++) {
printf("%d ", arr[i][j]);
}
printf("\n");
}

return 0;
}

2
In this example:

 arr is a 2D array with 3 rows and 4 columns.


 Nested loops are used to traverse the array row by row and column by column.

Introduction to Strings in C

In C, strings are arrays of characters. A string is terminated with a special character '\0' (null
character) to mark the end of the string.

For example:

#include <stdio.h>

int main() {
char str[] = "Hello, World!"; // String initialization

// Printing the string


printf("The string is: %s\n", str);

return 0;
}

 In this case, "Hello, World!" is an array of characters: ['H', 'e', 'l', 'l', 'o', ',', ' ', 'W', 'o',
'r', 'l', 'd', '!', '\0'].
 The printf function with the %s format specifier prints the entire string, stopping when
it encounters the '\0'.

6. Operations on Strings in C

C provides several standard library functions to perform common operations on strings, such
as concatenation, copying, and finding the length of a string. These functions are defined in
the header file <string.h>.

 String Length: strlen() returns the length of a string (not counting the null character).

#include <string.h>
int len = strlen(str); // Returns the length of str

 String Copy: strcpy() copies one string to another.

strcpy(str2, str1); // Copies the content of str1 into str2

 String Concatenation: strcat() concatenates two strings.

strcat(str1, str2); // Appends str2 to the end of str1

 String Comparison: strcmp() compares two strings.

int result = strcmp(str1, str2); // Returns 0 if str1 and str2 are equal
3
7. Example Program Using Strings

Here’s a simple program that demonstrates basic string operations in C:

#include <stdio.h>
#include <string.h> // Required for string functions

int main() {
char str1[50] = "Hello";
char str2[] = " World!";

// Concatenating two strings


strcat(str1, str2);
printf("After concatenation: %s\n", str1); // Output: Hello World!

// Finding the length of the string


printf("Length of str1: %lu\n", strlen(str1)); // Output: 12

// Copying strings
char str3[50];
strcpy(str3, str1);
printf("After copying: %s\n", str3); // Output: Hello World!

// Comparing strings
if (strcmp(str1, str3) == 0) {
printf("str1 and str3 are equal.\n");
} else {
printf("str1 and str3 are not equal.\n");
}

return 0;
}

4
UNIT IV Pointers & User Defined Data types: Pointers, dereferencing and address
operators, pointer and address arithmetic, array manipulation using pointers, User-
defined data types-Structures and Unions.

Pointers and User-Defined Data Types in C

In C, pointers are variables that store memory addresses. They are one of the most powerful
and complex features of C, allowing for direct memory manipulation. Alongside pointers,
user-defined data types like structures and unions allow us to define complex data types to
suit our needs.

1. Pointers in C

a. What is a Pointer?

A pointer is a variable that stores the memory address of another variable. Pointers can point
to variables of any data type, such as integers, floats, characters, etc.

int x = 10; // normal variable


int *p = &x; // pointer p stores the address of variable x

In this example:

 x is a normal integer variable.


 p is a pointer to an integer (int *), and it stores the memory address of x, which is
obtained using the address-of operator &.

b. Dereferencing a Pointer (* operator)

Dereferencing a pointer means accessing the value stored at the address the pointer is
pointing to. This is done using the * operator.

int x = 10;
int *p = &x; // p stores the address of x
printf("%d\n", *p); // Dereferencing p to get the value of x, Output: 10

In this case, *p gives the value of x (i.e., 10).

c. Address-of Operator (&)

The & operator is used to get the memory address of a variable. For example:

int x = 5;
printf("Address of x: %p\n", &x); // Prints the address of x

5
d. Pointer Arithmetic

Pointer arithmetic allows you to perform operations on pointers, such as incrementing or


decrementing them.

 Incrementing a pointer (p++): Moves the pointer to the next memory location of the
same type.
 Decrementing a pointer (p--): Moves the pointer to the previous memory location of
the same type.

Example:

int arr[] = {10, 20, 30};


int *p = arr; // Points to the first element of arr
printf("%d\n", *p); // Output: 10
p++; // Now p points to the second element
printf("%d\n", *p); // Output: 20

e. Array Manipulation Using Pointers

In C, arrays and pointers are closely related. An array name is a pointer to the first element of
the array.

Example:

int arr[] = {10, 20, 30};


int *p = arr; // p points to the first element of the array

// Access array elements using pointer arithmetic


for (int i = 0; i < 3; i++) {
printf("%d ", *(p + i)); // Dereferencing the pointer to access array elements
}
// Output: 10 20 30

Arrays with Pointers in C

In C programming, arrays and pointers are closely related. An array can be thought of as a
pointer to the first element of the array. This is important because it means that arrays can be
manipulated using pointers and vice versa.

1. Understanding Arrays and Pointers

 An array is a collection of elements of the same data type stored in contiguous


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

The key point is that the name of an array is essentially a pointer to the first element of the
array.

6
2. Array Name as a Pointer

When you declare an array in C, the name of the array behaves like a pointer to its first
element. For example:

int arr[5] = {1, 2, 3, 4, 5};

In this case, arr is a pointer to the first element of the array. You can access the elements of
the array using both the array indexing notation and pointer arithmetic.

3. Accessing Array Elements Using Pointers

 Array indexing: arr[i] accesses the i-th element of the array.


 Pointer arithmetic: *(arr + i) accesses the i-th element of the array.

Since arr is a pointer to the first element, arr + i gives the address of the i-th element, and
*(arr + i) dereferences that address to get the value stored there.

4. Example of Array Access Using Pointers

#include <stdio.h>

int main() {
int arr[5] = {10, 20, 30, 40, 50};

// Accessing array elements using array indexing


printf("Array element at index 2: %d\n", arr[2]);

// Accessing array elements using pointers


printf("Array element at index 2 using pointer: %d\n", *(arr + 2));

return 0;
}

Explanation:

 arr[2] accesses the element at index 2 (which is 30).


 *(arr + 2) also accesses the element at index 2 by performing pointer arithmetic.

5. Pointer Arithmetic with Arrays

Pointer arithmetic allows you to traverse the array using a pointer, and it can be used to
iterate over the elements of an array.

 arr + 1 gives the address of the second element.


 *(arr + 1) gives the value of the second element.
 Similarly, arr + i gives the address of the i-th element.

7
Example: Iterating Over an Array Using Pointers

#include <stdio.h>

int main() {
int arr[5] = {10, 20, 30, 40, 50};

// Using pointer to iterate over the array


for (int i = 0; i < 5; i++) {
printf("Element %d: %d\n", i, *(arr + i));
}

return 0;
}

6. Pointer to an Array

You can also declare a pointer to an entire array, though this is less common than the
approach where the pointer points to the first element of the array.

int arr[5] = {1, 2, 3, 4, 5};


int (*ptr)[5] = &arr; // Pointer to the entire array

 ptr is a pointer to an array of 5 integers.


 To access an element of the array via ptr, use the following syntax:

printf("%d\n", (*ptr)[2]); // Accessing the 3rd element (index 2)

7. Passing Arrays to Functions Using Pointers

When you pass an array to a function, you are actually passing the address of the first element
of the array (the pointer). This means the function can modify the original array.

Example: Passing Arrays to Functions Using Pointers


#include <stdio.h>

void modifyArray(int *arr, int size) {


for (int i = 0; i < size; i++) {
arr[i] *= 2; // Double each element
}
}

int main() {
int arr[5] = {1, 2, 3, 4, 5};

printf("Before modification:\n");
for (int i = 0; i < 5; i++) {
printf("%d ", arr[i]);
}
printf("\n");

8
modifyArray(arr, 5); // Pass array as pointer

printf("After modification:\n");
for (int i = 0; i < 5; i++) {
printf("%d ", arr[i]);
}
printf("\n");

return 0;
}

Explanation:

 The modifyArray() function accepts a pointer to the array (int *arr).


 Inside the function, the array is modified using the pointer notation.
 Changes are reflected in the main() function because the array is passed by reference.

8. Using Pointers with 2D Arrays

Pointers can also be used with multi-dimensional arrays, such as 2D arrays.

Example: Accessing 2D Arrays Using Pointers


#include <stdio.h>

int main() {
int arr[2][3] = {{1, 2, 3}, {4, 5, 6}};

// Accessing elements using pointer notation


printf("Element at [0][1]: %d\n", *(*(arr + 0) + 1)); // 2
printf("Element at [1][2]: %d\n", *(*(arr + 1) + 2)); // 6

return 0;
}

Explanation:

 arr is a 2D array.
 *(arr + 0) gives the address of the first row, and *(arr + 1) gives the address of the
second row.
 *(*(arr + i) + j) accesses the element at row i and column j.

Dynamic Memory Allocation in C:

In C, dynamic memory allocation allows you to allocate memory during runtime (i.e., when
the program is running), as opposed to statically allocated memory which is fixed at compile
time. This is useful when the size of data structures like arrays is not known at compile time.

The functions used for dynamic memory allocation in C are provided by the standard library
<stdlib.h>. These functions are:

9
 malloc(): Allocates a block of memory of the specified size. It does not initialize the
memory.
 calloc(): Allocates memory for an array of elements and initializes the memory to
zero.
 realloc(): Changes the size of an already allocated memory block. It can be used to
increase or decrease the size.
 free(): Deallocates previously allocated memory, releasing it back to the system.

Let’s go over each of these functions.

1. malloc() (Memory Allocation)

The malloc() function is used to allocate a block of memory of a specified size. It returns a
pointer to the allocated memory, or NULL if the memory allocation fails.

Syntax:
void *malloc(size_t size);

 size: The number of bytes to be allocated.


 Returns: A pointer to the allocated memory block. If the allocation fails, it returns
NULL.

Example:

#include <stdio.h>
#include <stdlib.h>

int main() {
int *ptr;

// Allocate memory for an array of 5 integers


ptr = (int *)malloc(5 * sizeof(int));

if (ptr == NULL) {
printf("Memory allocation failed\n");
return 1; // Return an error code
}

// Using the allocated memory


for (int i = 0; i < 5; i++) {
ptr[i] = i * 10; // Assigning values
}
// Printing the values
for (int i = 0; i < 5; i++) {
printf("ptr[%d] = %d\n", i, ptr[i]);
}
// Free the allocated memory
free(ptr);
return 0;
}

10
Explanation:

 malloc(5 * sizeof(int)) allocates memory for 5 integers.


 We use the pointer ptr to access and modify the memory block.
 Finally, we free the memory using free().

2. calloc() (Contiguous Allocation)

The calloc() function is similar to malloc(), but it initializes the allocated memory to zero.

Syntax:
void *calloc(size_t num, size_t size);

 num: The number of blocks to allocate.


 size: The size of each block (typically the size of a single element, like sizeof(int)).
 Returns: A pointer to the allocated memory, or NULL if allocation fails.

Example:

#include <stdio.h>
#include <stdlib.h>

int main() {
int *ptr;

// Allocate memory for 5 integers and initialize them to 0


ptr = (int *)calloc(5, sizeof(int));

if (ptr == NULL) {
printf("Memory allocation failed\n");
return 1; // Return an error code
}

// Printing the values (all should be 0 initially)


for (int i = 0; i < 5; i++) {
printf("ptr[%d] = %d\n", i, ptr[i]);
}

// Free the allocated memory


free(ptr);

return 0;
}

Explanation:

 calloc(5, sizeof(int)) allocates memory for 5 integers and sets all of them to zero.
 It’s particularly useful when you want to ensure that the memory is initialized to zero.

11
3. realloc() (Reallocation)

The realloc() function is used to resize a previously allocated block of memory. It can either
expand or shrink the size of the memory block. If the new memory block is larger, it may
move the block to a different location.

Syntax:
void *realloc(void *ptr, size_t size);

 ptr: A pointer to the previously allocated memory block.


 size: The new size of the block in bytes.
 Returns: A pointer to the reallocated memory block, or NULL if the reallocation fails.
If the memory block is moved, the old pointer becomes invalid, so it’s a good practice
to assign the return value to the original pointer.

Example:

#include <stdio.h>
#include <stdlib.h>

int main() {
int *ptr;

// Initially allocate memory for 3 integers


ptr = (int *)malloc(3 * sizeof(int));

if (ptr == NULL) {
printf("Memory allocation failed\n");
return 1; // Return an error code
}

// Assign values to the array


for (int i = 0; i < 3; i++) {
ptr[i] = i + 1;
}

// Print initial values


printf("Initial values:\n");
for (int i = 0; i < 3; i++) {
printf("ptr[%d] = %d\n", i, ptr[i]);
}

// Reallocate memory to hold 5 integers


ptr = (int *)realloc(ptr, 5 * sizeof(int));

if (ptr == NULL) {
printf("Reallocation failed\n");
return 1; // Return an error code
}

12
// Assign values to the newly allocated space
for (int i = 3; i < 5; i++) {
ptr[i] = (i + 1) * 10;
}

// Print the new values


printf("\nAfter reallocation:\n");
for (int i = 0; i < 5; i++) {
printf("ptr[%d] = %d\n", i, ptr[i]);
}

// Free the allocated memory


free(ptr);

return 0;
}

Explanation:

 Initially, we allocate memory for 3 integers using malloc().


 After using the memory, we resize it to hold 5 integers using realloc().
 The realloc() function returns a new pointer to the resized memory block. If the
reallocation is successful, the old pointer should no longer be used.

4. free() (Memory Deallocation)

The free() function is used to deallocate memory that was previously allocated using
malloc(), calloc(), or realloc(). After calling free(), the pointer becomes dangling and should
not be used again unless it’s reassigned.

Syntax:
void free(void *ptr);

 ptr: A pointer to the memory block to be freed.

Example:

#include <stdio.h>
#include <stdlib.h>

int main() {
int *ptr = (int *)malloc(5 * sizeof(int));

if (ptr == NULL) {
printf("Memory allocation failed\n");
return 1;
}

// Using the allocated memory


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

13
ptr[i] = i * 10;
}

// Print the values


for (int i = 0; i < 5; i++) {
printf("ptr[%d] = %d\n", i, ptr[i]);
}

// Free the allocated memory


free(ptr);

return 0;
}

Explanation:

 After using the memory, we call free(ptr) to release the allocated memory.
 Important: After calling free(), the pointer ptr becomes invalid. You should not
dereference it, and ideally, set it to NULL to prevent accidental use.

User-Defined Data Types in C

a. Structures

A structure in C is a user-defined data type that allows grouping variables of different types
under a single name.

Example of a structure:

#include <stdio.h>
struct Person {
char name[50];
int age;
};

int main() {
struct Person p1 = {"John", 30}; // Initializing a structure

// Accessing structure members using the dot (.) operator


printf("Name: %s\n", p1.name);
printf("Age: %d\n", p1.age);

return 0;
}

 struct Person is a structure that holds a name (array of characters) and an age
(integer).
 We can access the structure members using the dot . operator (p1.name, p1.age).

14
Pointer to Structure

We can use pointers with structures to dynamically access and modify their members.

#include <stdio.h>

struct Person {
char name[50];
int age;
};

int main() {
struct Person p1 = {"Alice", 25};
struct Person *p2 = &p1; // p2 is a pointer to the structure p1

// Accessing structure members using a pointer and the arrow (->) operator
printf("Name: %s\n", p2->name); // Output: Alice
printf("Age: %d\n", p2->age); // Output: 25

return 0;
}

 The -> operator is used to access structure members via a pointer.

b. Unions

A union is similar to a structure, but all members of a union share the same memory location.
This means a union can store one of its members at a time, and the memory used by the union
is equal to the size of its largest member.

Example of a union:

#include <stdio.h>

union Data {
int i;
float f;
char str[20];
};

int main() {
union Data data;

// Storing an integer
data.i = 10;
printf("data.i: %d\n", data.i); // Output: 10

// Storing a float
data.f = 3.14;
printf("data.f: %.2f\n", data.f); // Output: 3.14

15
// Storing a string
strcpy(data.str, "Hello, world!");
printf("data.str: %s\n", data.str); // Output: Hello, world!

return 0;
}

 Key point: A union can hold only one of its members at a time, and the last stored
member will overwrite any previously stored members.

Memory Usage of Union vs Structure

 Structure: Each member has its own memory, so the size of the structure is the sum of
the sizes of all its members.
 Union: All members share the same memory, so the size of the union is the size of the
largest member.

Example: Comparing structure and union memory usage:


#include <stdio.h>

struct Person {
int age;
char name[50];
};

union Data {
int i;
float f;
char str[20];
};

int main() {
printf("Size of struct Person: %lu\n", sizeof(struct Person)); // Size depends on the
members
printf("Size of union Data: %lu\n", sizeof(union Data)); // Size equals the size of the
largest member

return 0;
}

 The sizeof operator is used to determine the memory size of the structure or union.

16
UNIT V Functions & File Handling
Introduction to Functions, Function Declaration and Definition, Function call Return
Types and Arguments, modifying parameters inside functions using pointers, arrays as
parameters. Scope and Lifetime of Variables, Basics of File Handling

Functions & File Handling in C

Functions in C allow you to break down a program into smaller, manageable parts, making
the code more modular and easier to maintain. Functions can be used to perform specific
tasks, which can be reused throughout the program. In addition, file handling in C allows for
reading from and writing to files, providing a way to store data persistently.

1. Introduction to Functions in C

A function is a block of code that performs a specific task. It can take input in the form of
parameters and return a result. Functions help make programs more organized and easier to
debug.

General Syntax of a Function:


return_type function_name(parameter_list) {
// body of the function
return value; // if return_type is not void
}

2. Function Declaration and Definition

 Function Declaration (also called function prototype) informs the compiler about the
function's name, return type, and parameters before its actual use.
 Function Definition provides the actual implementation of the function.

Example:
#include <stdio.h>

// Function Declaration
int add(int, int);

int main() {
int result = add(5, 3); // Function Call
printf("Sum: %d\n", result);
return 0;
}

// Function Definition
int add(int a, int b) {
return a + b;
}

17
In this example:

 The function add() is declared with the prototype int add(int, int);.
 It is then defined below with the actual logic return a + b;.
 Finally, in the main() function, it is called with arguments 5 and 3.

3. Function Call, Return Types, and Arguments

 Function Call: A function is called by passing arguments that match the function's
parameters.
 Return Type: The function can return a value of a specific type (e.g., int, float, void).
 Arguments: Functions can take parameters (also called arguments), which are used
within the function.

Example with Return Type and Arguments:


#include <stdio.h>

float multiply(float a, float b) {


return a * b;
}

int main() {
float result = multiply(4.5, 2.0); // Function call
printf("Multiplication result: %.2f\n", result);
return 0;
}

In this example:

 multiply() takes two float arguments and returns a float.


 The main() function calls multiply() and stores the result.

4. Modifying Parameters Inside Functions Using Pointers

In C, parameters are passed by value by default, meaning that the function receives a copy of
the value, and changes made inside the function do not affect the original variable. To modify
the original variable, we use pointers.

Example of Modifying Parameters Using Pointers:


#include <stdio.h>
void modifyValue(int *x) {
*x = 100; // Dereferencing the pointer to modify the value of x
}

int main() {
int num = 5;
modifyValue(&num); // Passing the address of num
printf("Modified value: %d\n", num); // Output: 100
return 0;
}

18
In this example:

 The modifyValue() function takes a pointer to an int and modifies the value at that
address.
 The address of num is passed to the function using the & operator.

5. Arrays as Function Parameters

Arrays can be passed to functions either by passing the entire array or by passing a pointer to
the array. When an array is passed, the function receives the base address of the array.

Example with Array as a Parameter:

include <stdio.h>
void printArray(int arr[], int size) {
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}

int main() {
int arr[] = {1, 2, 3, 4, 5};
printArray(arr, 5); // Passing array and its size
return 0;
}

In this example:

 The function printArray() takes an array (int arr[]) and its size (int size).
 The array is passed by reference (the base address is passed).

6. Scope and Lifetime of Variables

In C, the scope and lifetime of variables are important concepts:

a. Scope:

 The scope of a variable determines where it can be accessed (i.e., which functions or
blocks of code it can be used in).
o Local variables: Defined inside a function or block and can only be used
within that function/block.
o Global variables: Defined outside of any function and can be accessed
anywhere in the program.

b. Lifetime:

 The lifetime of a variable refers to how long it exists in memory.


o Local variables: Exist only during the execution of the function or block.
o Global variables: Exist for the entire duration of the program.

19
Example:
#include <stdio.h>

int globalVar = 10; // Global variable

void function() {
int localVar = 5; // Local variable
printf("Local variable: %d\n", localVar);
printf("Global variable: %d\n", globalVar);
}

int main() {
function();
printf("Global variable in main: %d\n", globalVar);
return 0;
}

In this example:

 globalVar is a global variable and can be accessed in both function() and main().
 localVar is local to function() and cannot be accessed outside it.

7. Basics of File Handling in C

File handling in C allows you to read from and write to files, which is essential for persistent
data storage. The C standard library provides functions to handle file operations.

a. File Operations in C:

 Opening a file: Use fopen() to open a file.


 Reading from a file: Use functions like fscanf() or fgets().
 Writing to a file: Use functions like fprintf() or fputs().
 Closing a file: Use fclose() to close the file after the operation is done.

b. Opening a File
FILE *fptr;
fptr = fopen("example.txt", "w"); // "w" mode for writing
if (fptr == NULL) {
printf("Error opening file.\n");
return 1;
}

Modes for opening files:

 "r": Read mode


 "w": Write mode (creates a new file or truncates an existing file)
 "a": Append mode (opens the file for writing at the end)
 "r+": Read and write mode
 "w+": Write and read mode (creates a new file or truncates an existing file)

20
c. Reading from and Writing to Files
#include <stdio.h>

int main() {
FILE *fptr;
char str[] = "Hello, world!";

// Writing to a file
fptr = fopen("example.txt", "w");
if (fptr == NULL) {
printf("Error opening file for writing.\n");
return 1;
}
fprintf(fptr, "%s\n", str);
fclose(fptr);

// Reading from the file


char buffer[100];
fptr = fopen("example.txt", "r");
if (fptr == NULL) {
printf("Error opening file for reading.\n");
return 1;
}
fgets(buffer, sizeof(buffer), fptr);
printf("Content of the file: %s\n", buffer);
fclose(fptr);

return 0;
}
d. Closing a File

It is important to always close a file after you are done with it using fclose() to free the
resources associated with the file.

fclose(fptr); // Close the file after reading/writing

21

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy