0% found this document useful (0 votes)
110 views33 pages

FOP-2 Question Bank Solutions Unit-1, 2, 3 & 4

Uploaded by

photosofthk
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)
110 views33 pages

FOP-2 Question Bank Solutions Unit-1, 2, 3 & 4

Uploaded by

photosofthk
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/ 33

FOP-2 Question Bank Solutions

Unit-1 Pointers
Q1) Define an array of 10 integer pointers.
Ans 1)

Q2) Write a program that uses a function pointer as a function argument.


Ans 2) Explanation:

• We define a function pointer type Operation which points to a function that


takes two int parameters and returns an int.
• The performOperation function takes two integers x and y and a function
pointer op as arguments. It calls the function pointed to by op with x and y as
arguments.
• In the main function, we prompt the user to enter two numbers and store them
in num1 and num2.

Page 1 of 33
• We then call performOperation with num1, num2, and the add function
pointer as arguments.
• The add function simply adds the two numbers and returns the result.
• Finally, we print the sum obtained from the performOperation function call.

Page 2 of 33
Q3) Give the meaning of int (*f)(int,int) and int *f(int,int).
Ans 3) The expressions `int (*f)(int, int)` and `int *f(int, int)` are both related to
function pointers in C, but they have different meanings:

1. `int (*f)(int, int)`: This declares a pointer `f` to a function that takes two `int`
arguments and returns an `int`. The syntax `(*f)` denotes that `f` is a pointer,
and `(int, int)` specifies the parameter types of the function pointed to by `f`.
This is commonly used to declare function pointers.

2. `int *f(int, int)`: This declares a function `f` that takes two `int` arguments
and returns a pointer to an `int`. The `*` before `f` indicates that `f` is a function
returning a pointer, and `(int, int)` specifies the parameter types of the function
`f`. This is a function declaration.

In summary:

- `int (*f)(int, int)`: Declares a function pointer named `f`.


- `int *f(int, int)`: Declares a function named `f` that returns a pointer to an
`int`.

Q4) What is Pointer in C? Explain its advantages.


Ans 4) In C, a pointer is a special variable that stores the memory address of
another variable. Instead of holding the actual value of the data, a pointer holds
the address where the data is stored in memory. This allows for indirect access
to the data stored in memory. Pointers play a crucial role in C programming for
various tasks such as dynamic memory allocation, accessing hardware,
implementing data structures, and passing parameters by reference to functions.

Pointers in C provide powerful capabilities for memory management, efficient


data access, and low-level manipulation of memory addresses. However, they
also require careful handling to avoid common pitfalls such as segmentation
faults, dangling pointers, and memory leaks.

Here are advantages of using pointers in C:

1. **Dynamic Memory Allocation**: Pointers allow dynamic memory


allocation, which means memory can be allocated or deallocated at runtime.
This flexibility is crucial for implementing data structures like linked lists,
trees, and dynamic arrays. Functions like `malloc()`, `calloc()`, and `realloc()`
are used to allocate memory dynamically, and pointers are used to manage this
memory.

Page 3 of 33
2. **Passing Parameters by Reference**: In C, function arguments are passed
by value by default, meaning a copy of the data is passed to the function.
However, using pointers, you can pass parameters by reference, allowing the
function to modify the original data. This is useful when dealing with large data
structures or when you need to modify variables in a function and reflect those
changes outside the function scope.

3. **Efficient Memory Management**: Pointers enable efficient memory


management by allowing data to be accessed directly in memory. This direct
access can lead to faster execution times and reduced memory overhead
compared to alternative data access methods, especially when dealing with
large datasets.

Q5) How to initialize Pointer? Explain arrays of pointer using suitable sample
program.

Ans 5) You can initialize a pointer by assigning it the address of an existing


variable using the address-of operator &. For example:

int x = 10;
int *ptr = &x; // ptr now points to the memory address of variable x

When initializing arrays of pointers, each element of the array holds the address
of another variable or memory location. Here's a simple example demonstrating
arrays of pointers:

In the following program:


• We declare an array of three integer pointers ptr_array.
• We also declare an array arr containing three integers.
• We assign the addresses of elements in arr to ptr_array.
• We then access and print the values stored in arr using the pointers in
ptr_array.

This example illustrates the concept of arrays of pointers, where each element
of the array holds the address of another variable or memory location. It's a
fundamental concept in C programming, often used in scenarios like arrays of
strings, dynamic memory allocation, and data structure implementations.

Page 4 of 33
Q6) What is a pointer? How and when it is used? How it is initialized?
Ans 6) A pointer in C is a variable that stores the memory address of another
variable. It allows indirect access to the memory location where data is stored,
enabling manipulation and interaction with that data.
Pointers are extensively used in C for various purposes, such as dynamic
memory allocation, passing arguments to functions by reference, accessing
hardware, and implementing data structures like linked lists and trees.

How and When Pointers Are Used:


• Dynamic Memory Allocation: Pointers are used to allocate memory
dynamically during program execution. This enables programs to manage
memory efficiently and handle data structures of varying sizes.
• Passing Arguments by Reference: Pointers allow functions to modify
variables outside their scope by passing the address of those variables. This
is useful when you want a function to alter the original data rather than
working with a copy.
• Accessing Hardware: In embedded systems and low-level programming,
pointers are used to access hardware registers and memory-mapped I/O
locations directly.
Page 5 of 33
• Implementing Data Structures: Pointers are crucial for implementing
complex data structures like linked lists, trees, and graphs. They enable
efficient manipulation and traversal of these structures by storing references
to other elements.
Pointers can be initialized by assigning them the address of another variable
using the address-of operator &. Here's a simple example demonstrating the
initialization of a pointer:

In this code:
• We declare an integer variable num to store an integer value.
• We declare a pointer variable ptr without initializing it.
• We then assign the address of the variable num to the pointer variable ptr
using the address-of operator &.
• Finally, we print the value of num, the address of num, the value of ptr
(which holds the address of num), and the value stored at the address pointed
to by ptr.
This simple code demonstrates how pointers are initialized and used to
indirectly access the memory location of another variable in C.

Page 6 of 33
Q7) What is Pointer in C? Explain its advantages. Also write a program to swap
two elements using pointer.
Ans 7) Refer to answer 4

In this program:
• We define a function swap that takes two integer pointers as arguments.
• Inside the swap function, we use pointer dereferencing (*) to access the
values stored at the memory addresses pointed to by a and b, and then swap
these values.
Page 7 of 33
• In the main function, we declare two integer variables num1 and num2.
• We prompt the user to input two numbers, and store them in num1 and num2.
• We call the swap function, passing the addresses of num1 and num2 as
arguments, to swap their values.
• Finally, we print the original and swapped values of num1 and num2.

Q8) Explain call by value (pass by value) and call by reference (pass by
reference) with examples in brief.
Ans 8)
Call by Value (Pass by Value):
In call by value, the value of the actual parameters (arguments) is copied to the
formal parameters of the function. Any modifications made to the formal
parameters inside the function do not affect the actual parameters outside the
function.

Output:

Page 8 of 33
Explanation:
• The increment function takes an integer parameter x.
• Inside the main function, num is initialized to 10.
• When increment(num) is called, the value of num (10) is passed to x.
• Inside the increment function, x is incremented to 11.
• However, the increment operation only affects the local variable x, and does
not modify the original num variable.
• Therefore, after the function call, num remains unchanged at its original
value (10).

Call by Reference (Pass by Reference):


In call by reference, instead of passing the values of the variables, we pass the
addresses (pointers) of the variables. This allows the function to directly modify
the original variables.

Output:

Page 9 of 33
Explanation:
• The increment function takes an integer pointer x.
• Inside the main function, num is initialized to 10.
• When increment(&num) is called, the address of num is passed to x.
• Inside the increment function, the value at the address pointed to by x is
incremented using the dereference operator (*x)++.
• This modification directly affects the original variable num.
• Therefore, after the function call, num is incremented to 11.
Q9) What is pointer to pointer? Write suitable example to demonstrate the
concept.
Ans 9) A pointer to a pointer, also known as a double pointer, is a pointer that
points to the memory address of another pointer. It is used to create dynamic
data structures such as linked lists of arrays and to implement multi-level
indirection.

Output:
Value of num using ptr1: 10
Value of num using ptr2: 10

Page 10 of 33
In this code:
• We declare an integer variable num.
• We declare a pointer to an integer ptr1.
• We declare a pointer to a pointer to an integer ptr2.
• We assign the address of num to ptr1.
• We assign the address of ptr1 to ptr2.
• We use ptr1 to access the value of num and print it.
• We use ptr2 to access the value of num indirectly through two levels of
indirection and print it.

Q10) Explain the concept of function returning pointers with syntax.


Ans 10)

Complex question hai, last mein krna agar time ho toh, nhi toh leave this
question

In C programming, a function can return a pointer just like it can return any
other data type. Returning a pointer from a function allows you to dynamically
allocate memory inside the function and then pass the address of that memory
back to the caller. This is useful when you want to create and manipulate data
structures such as arrays or linked lists.

In this code:
• The createArray function dynamically allocates memory for an array of
integers based on the provided size.
• It initializes the array elements with some values (in this case, consecutive
even numbers).
• The function returns the pointer to the dynamically allocated array back to
the caller.
• In the main function, we call createArray and store the returned pointer in
the arr variable.
• We then use this pointer to access and print the elements of the dynamically
allocated array.
• Finally, we free the memory allocated for the array using the free function to
prevent memory leaks.

The output of the provided C code will be:

Dynamically allocated array elements:


02468

Page 11 of 33
Page 12 of 33
Unit-2 Structures
Q11) Define an array of structure with integer, string and float as members. Size
of array is 10.
Ans 11)

Page 13 of 33
In this code:
• We define a structure named Data with integer (id), string (name), and float
(value) members.
• We declare an array of Data structures named dataArray with a size of 10.
• We populate the array with sample data using a loop.
• We print the contents of the array, displaying the ID, name, and value of each
structure member for each item in the array.

Q12) Define Structure and write the general syntax for declaring and accessing
members.
Ans 12) In programming, a structure is a composite data type that groups
together variables of different types under a single name. It allows you to
organize related data items more efficiently. Here's a general definition and
syntax for declaring and accessing members of a structure:

1. Structure Definition:
A structure is typically defined using a struct keyword followed by a name for
the structure. Inside the structure definition, you declare variables of various
types to represent the members of the structure.

struct structure_name {
data_type1 member1;
data_type2 member2;
// Additional members...
};

2. Declaration:
Once the structure is defined, you can declare variables of that structure type.

struct structure_name variable_name;

3. Initialization:
You can also initialize structure variables during declaration.

struct structure_name variable_name = { value1, value2, ... };

4. Accessing Members:
You can access members of a structure variable using the dot (.) operator.

variable_name.member1 = value; // Accessing member1


variable_name.member2 = value; // Accessing member2

Page 14 of 33
Q13) What is structure? How can we access structure members? Clear use of
nested structure using example. Compare structure with union
Ans 13) A structure, also known as a struct, is a composite data type in
programming that allows you to group together variables of different types
under a single name. It provides a way to organize related data items efficiently.
Each member within a structure has its own data type and name, and these
members can be accessed individually.
Accessing Members:
You can access members of a structure variable using the dot (.) operator.
————————————————————————————————
variable_name.member1 = value; // Accessing member1
variable_name.member2 = value; // Accessing member2
————————————————————————————————

Page 15 of 33
In this example, we have two structures: Point to represent a point in a 2D space
with coordinates x and y, and Rectangle to represent a rectangle using two Point
structures for its top-left and bottom-right corners. We then declare a variable
rect of type Rectangle and set values for its nested structure members (topLeft
and bottomRight). Finally, we access and print the coordinates of the rectangle's
corners using nested structure member access.

Structure vs. Union:

Structures and unions are both composite data types in C, but they have some
key differences:

1. Memory Allocation:
• In a structure, each member has its own memory location, and the size of
the structure is the sum of the sizes of its members.
• In a union, all members share the same memory location, and the size of
the union is determined by the size of its largest member.
2. Usage:
• Structures are used to group related data items together.
• Unions are used when you want to store different types of data in the
same memory location, but you only need to access one member at a time.
C Code:
————————————————————————————————
struct Rectangle {
int width;
int height;
};

union Shape {
int radius;
struct Rectangle rect;
};
————————————————————————————————
In this example, a Rectangle structure is used to represent a rectangle with
width and height, while a Shape union can represent either a rectangle or a
circle (with a radius).

Q14) Give one example for Array of structure and explain the meaning.
Ans 14) Refer question 11

Page 16 of 33
Q15) What is structure? How does a structure differ from an array? How is an
array of structure initialized?

Ans 15) A structure, also known as a struct, is a composite data type in


programming that allows you to group together variables of different types
under a single name. Each member within a structure has its own data type and
name, and these members can be accessed individually. Structures provide a
way to organize related data items efficiently.

Differences between Structure and Array:

1. Composition:
• A structure can hold variables of different data types as its members.
• An array holds variables of the same data type in a contiguous block of
memory.

2. Access:
• Structure members are accessed using the dot (.) operator, providing direct
access to individual elements.
• Array elements are accessed using index notation ([]), and elements are
accessed sequentially.

3. Memory Allocation:
• Memory for each structure member is allocated separately, and the size of a
structure is the sum of the sizes of its members.
• Array elements are allocated consecutively in memory, and the size of an
array is the product of the size of its elements and the number of elements.

In the following example:


• We define a structure called Point to represent a point in a 2D space with
coordinates x and y.
• We declare an array of Point structures called points with a size of 3.
• During initialization, we use designated initializers to set values for each
element of the array. Each element is initialized with braces {} containing the
values for the x and y coordinates.
• We then access and print the initialized values of each point in the array
using a loop.

Page 17 of 33
Q16) Distinguish between “structure” and “array”. Discuss the meaning and
purpose of following:(1) struct keyword (2) typdef keyword (3) sizeof operator.

Ans 16)

1. **Structure**:
- A structure, also known as a "struct" in many programming languages, is a
composite data type that groups together variables of different data types under
a single name.
- Each variable within a structure is called a member or a field. These
members can be of any data type, including primitive types (like integers,
floats, characters) or even other structures.

Page 18 of 33
- Structures allow you to create custom data types to represent complex
entities in your program. For example, you might create a "Person" structure
with members such as name, age, and address.
- Structures are typically used to organize related data into a single unit,
making it easier to manage and manipulate.

2. **Array**:
- An array is a data structure that stores a fixed-size collection of elements of
the same data type.
- Elements in an array are accessed by their index, which is typically an
integer value starting from zero.
- Arrays are used to store multiple values of the same data type sequentially in
memory, allowing for efficient access to individual elements based on their
positions.
- Unlike structures, which can store variables of different data types, arrays
can only store elements of a single data type. For example, an array of integers
can only hold integer values.
- Arrays are commonly used for tasks such as storing lists of items, managing
collections of data, and implementing various algorithms.

In summary, while both structures and arrays are used for organizing and
storing data in computer programs, structures are used to group together
variables of different data types under a single name, whereas arrays are used to
store a fixed-size collection of elements of the same data type in a sequential
manner.

1. **struct keyword**:
- The `struct` keyword is used in many programming languages, including C
and C++, to define a new user-defined data type known as a "structure."
- Structures allow you to combine multiple variables of different data types
under a single name.
- The purpose of using the `struct` keyword is to create custom data types that
represent complex entities in your program. For example, you might create a
`struct` to represent a "Person" with members such as name, age, and address.
- Structures provide a way to organize related data into a single unit, making
it easier to manage and manipulate.

2. **typedef keyword**:
- The `typedef` keyword is used to create an alias or a new name for an
existing data type.

Page 19 of 33
- This keyword is particularly useful for defining complex data types or
simplifying complex declarations, especially when dealing with structures,
pointers, or function pointers.
- The purpose of `typedef` is to improve code readability, enhance portability,
and simplify the declaration of complex types.
- For example, you can use `typedef` to define a new name for a structure,
making it easier to declare variables of that type without having to use the
`struct` keyword each time.

3. **sizeof operator**:
- The `sizeof` operator is used to determine the size, in bytes, of a variable or
a data type in memory.
- It is an operator rather than a keyword, and it returns the size of its operand.
- The purpose of `sizeof` is to enable developers to write portable code by
providing a way to determine the size of data types and structures at compile
time.
- It is commonly used in scenarios such as memory allocation, serialization,
and low-level programming where knowledge of data sizes is critical.
- For example, `sizeof(int)` would return the size of an integer in bytes, and
`sizeof(struct Person)` would return the size of a `Person` structure in bytes.

In summary, the `struct` keyword is used to define new data types called
structures, the `typedef` keyword is used to create aliases for existing data
types, and the `sizeof` operator is used to determine the size of variables or data
types in memory. Each of these concepts serves a distinct purpose in
programming, contributing to code organization, readability, and portability.

Q17) What is structure give an example?


Ans 17) Refer question 12.
Q18) Explain structure within structure. Write down its syntax with example.
Ans 18) Refer question 13.

Q19) Differentiate Structure vs union.


Ans 19)

1. **Structure**:
- A structure, often abbreviated as `struct`, is a composite data type that allows
you to group together variables of different data types under a single name.
- Each variable within a structure is called a member or a field, and these
members can be accessed individually.
- Structures are used to create custom data types to represent complex entities,
such as a person with attributes like name, age, and address.

Page 20 of 33
- Memory is allocated for each member of the structure separately, and the
total size of a structure is the sum of the sizes of its individual members.
- Structures are typically used when you want to group related but distinct
pieces of data together.

2. **Union**:
- A union is also a composite data type like a structure, but it only allows one
member to be stored in memory at a time, sharing the same memory location.
- Unlike structures, where each member has its memory space, unions allocate
memory that is large enough to hold the largest member.
- All members of a union share the same memory location, so modifying one
member can affect the values of other members.
- Unions are useful when you want to store different types of data in the same
memory location and only need to access one of them at a time.
- Common use cases for unions include implementing variant data types,
optimizing memory usage, and working with hardware registers where multiple
data types share the same memory location.

In summary, structures are used to group together variables of different data


types under a single name, allowing access to each member individually, while
unions allow you to store different types of data in the same memory location,
with only one member accessible at a time. Structures are suitable for
organizing related but distinct pieces of data, while unions are used when you
need to conserve memory or work with overlapping data.

Q20) Write a program to illustrate the use of structure pointers.


Ans 20) In the following program:
• We define a structure called Person with members name and age.
• We declare a structure variable person1 of type Person.
• We declare a pointer to a Person structure called personPtr.
• We assign the address of person1 to personPtr.
• We use -> operator with the pointer to access structure members.
• We take input for name and age using the pointer.
• We display the information using the pointer.
This program demonstrates how to declare, initialize, and use structure pointers
to access and manipulate structure members.

Note: '->' is used with pointers to access structure members.

Page 21 of 33
Page 22 of 33
Unit-3 Dynamic Memory Allocation
Q21) How can you allocate memory dynamically for 10 floating point
numbers?
Ans 21)

Page 23 of 33
In this program:
• We declare a pointer floatArray to hold the address of the dynamically
allocated memory.
• We use malloc to allocate memory for an array of 10 floating-point numbers
(10 * sizeof(float) bytes).
• We check if the memory allocation was successful by ensuring that the
pointer is not NULL.
• We input values for the array using a loop.
• We display the entered values using another loop.
• Finally, we free the dynamically allocated memory using the free function to
prevent memory leaks.
Make sure to include <stdlib.h> header file for malloc and free functions.

Q22) Recall the definition of dynamic memory allocation? Give example of


malloc( ) and calloc (). Differentiate between malloc and calloc?

Ans 22) Dynamic memory allocation refers to the process of allocating memory
at runtime (during program execution) rather than at compile time. This allows
programs to allocate memory as needed, enabling flexibility and efficiency in
memory usage.

In languages like C and C++, dynamic memory allocation is typically


performed using functions like `malloc`, `calloc`, `realloc`, and `free`. Here's a
brief overview of each:

1. **malloc**: Allocates a block of memory of a specified size in bytes. It


returns a pointer to the beginning of the allocated memory block.

2. **calloc**: Allocates memory for an array of elements, initializes them to


zero, and returns a pointer to the beginning of the allocated memory block. It
takes two arguments: the number of elements to allocate memory for and the
size of each element in bytes.

3. **realloc**: Resizes a previously allocated memory block to a new size. It


takes two arguments: a pointer to the previously allocated memory block and
the new size in bytes. It returns a pointer to the beginning of the resized
memory block.

4. **free**: Releases a block of memory that was previously allocated


dynamically. It deallocates the memory, making it available for reuse.

Page 24 of 33
Dynamic memory allocation allows programs to allocate memory as needed,
which is especially useful when the size of data structures is not known at
compile time or when memory requirements vary during program execution.
However, it's important to manage dynamically allocated memory properly to
avoid memory leaks, where allocated memory is not deallocated properly,
leading to inefficient memory usage over time.

`malloc` and `calloc` are both functions in C used for dynamic memory
allocation, but they have some differences in their behavior:

1. **malloc**:
- The `malloc` function allocates a block of memory of a specified size in
bytes.
- It takes a single argument, which is the size of the memory block to allocate
in bytes.
- The memory allocated by `malloc` is uninitialized, meaning it contains
garbage values. It does not initialize the memory to zero.
- If `malloc` is unable to allocate the requested amount of memory, it returns a
`NULL` pointer.

2. **calloc**:
- The `calloc` function allocates memory for an array of elements, initializing
them to zero.
- It takes two arguments: the number of elements to allocate memory for and
the size of each element in bytes.
- The total amount of memory allocated by `calloc` is equal to the product of
the number of elements and the size of each element.
- `calloc` initializes the allocated memory to zero, ensuring that all bytes in
the allocated memory block are set to zero.
- If `calloc` is unable to allocate the requested amount of memory, it returns a
`NULL` pointer.

In summary, `malloc` and `calloc` both allocate memory dynamically, but


`malloc` allocates uninitialized memory, while `calloc` initializes the allocated
memory to zero. The choice between `malloc` and `calloc` depends on whether
you need the allocated memory to be initialized to zero and the specific
requirements of your program.

Page 25 of 33
CODE
#include <stdio.h>
#include <stdlib.h>

int main() {
// Example using malloc
int *ptr1;
int size1 = 5;

// Allocate memory for an array of integers using malloc


ptr1 = (int *)malloc(size1 * sizeof(int));

// Check if memory allocation was successful


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

// Example using calloc


int *ptr2;
int size2 = 5;

// Allocate memory for an array of integers using calloc


ptr2 = (int *)calloc(size2, sizeof(int));

// Check if memory allocation was successful


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

// Displaying the allocated memory addresses


printf("Memory allocated successfully:\n");
printf("ptr1 address: %p\n", (void *)ptr1);
printf("ptr2 address: %p\n", (void *)ptr2);

// Freeing the allocated memory


free(ptr1);
free(ptr2);

return 0;
}

Page 26 of 33
In this example:
• We first allocate memory for an array of integers using malloc and calloc.
• We check if memory allocation was successful by verifying that the pointers
are not NULL.
• We display the memory addresses of the allocated memory blocks.
• Finally, we free the dynamically allocated memory using the free function to
prevent memory leaks.
Both malloc and calloc are used to allocate memory dynamically, but malloc
allocates uninitialized memory, while calloc initializes the allocated memory to
zero.

Q23) Explain dynamic memory allocation.


Ans 23) Refer question 21 and 22.

Unit-4 File Management


Q24) Write syntax of fseek() function and explain fseek(fp,-10,1) and
fseek(fp,10,0).

Ans 24) The `fseek()` function in C is used to set the file position indicator for a
given file stream. It allows you to move the position indicator within a file,
which can be useful for random access or seeking within files.

Syntax of `fseek()` function:

int fseek(FILE *stream, long int offset, int origin);

- `stream`: Pointer to a file stream.


- `offset`: Number of bytes to offset from the origin.
- `origin`: Specifies the starting point for the offset. It can be one of the
following constants:
- `SEEK_SET`: Beginning of the file.
- `SEEK_CUR`: Current position of the file pointer.
- `SEEK_END`: End of the file.

Explanation of `fseek(fp, -10, 1)`:


- This statement seeks 10 bytes backward from the current position
(`SEEK_CUR`) in the file associated with the file pointer `fp`.
- The `offset` is `-10`, indicating that the position should be moved 10 bytes
backward.
- The `origin` is `1`, indicating the current position (`SEEK_CUR`).

Page 27 of 33
Explanation of `fseek(fp, 10, 0)`:
- This statement seeks 10 bytes forward from the beginning (`SEEK_SET`) of
the file associated with the file pointer `fp`.
- The `offset` is `10`, indicating that the position should be moved 10 bytes
forward.
- The `origin` is `0`, indicating the beginning of the file (`SEEK_SET`).
Q25) Distinguish between the following functions:
1. getc and getchar.
2. fprintf and printf.
3. feod and ferror.

Ans 25) Let's differentiate between the following pairs of functions:

1. **getc and getchar**:

- **getc**:
- `getc` is used to read a character from a specified file stream.
- It takes a file pointer as an argument and returns the next character from
the file.
- If successful, it returns the character read as an `unsigned char` cast to an
`int`, or `EOF` if the end of the file is reached or if an error occurs.

- **getchar**:
- `getchar` is used to read a character from the standard input (stdin).
- It does not take any arguments and reads a character from the standard
input stream.
- If successful, it returns the next character read as an `unsigned char` cast
to an `int`, or `EOF` if the end of the input stream is reached or if an error
occurs.

- **Difference**:
- `getc` reads from a specified file stream, whereas `getchar` reads from
the standard input.
- Both functions return the next character read, but their sources of input
differ.

2. **fprintf and printf**:

- **fprintf**:
- `fprintf` is used to write formatted data to a specified file stream.

Page 28 of 33
- It takes a file pointer as its first argument, followed by a format string
and additional arguments to be formatted.
- It writes the formatted data to the specified file stream.

- **printf**:
- `printf` is used to write formatted data to the standard output (stdout).
- It takes a format string and additional arguments to be formatted.
- It writes the formatted data to the standard output stream.

- **Difference**:
- `fprintf` writes formatted data to a specified file stream, while `printf`
writes to the standard output.
- Both functions use the same formatting syntax but differ in their output
destinations.

3. **feof and ferror**:

- **feof**:
- `feof` is used to check whether the end-of-file indicator for a given file
stream has been set.
- It takes a file pointer as an argument and returns a non-zero value if the
end-of-file indicator is set, indicating that the end of the file has been reached.

- **ferror**:
- `ferror` is used to check whether an error indicator for a given file stream
has been set.
- It takes a file pointer as an argument and returns a non-zero value if the
error indicator is set, indicating that an error has occurred during an operation
on the file stream.

- **Difference**:
- `feof` checks for the end-of-file condition, while `ferror` checks for error
conditions.
- `feof` returns non-zero if the end-of-file indicator is set, while `ferror`
returns non-zero if the error indicator is set.
- Both functions are used to check the state of a file stream after reading or
writing operations.

Q26) Write a program to illustrate the use of fputc( ) and fputs( ).


Ans 26)

Page 29 of 33
CODE:
#include <stdio.h>

int main() {
FILE *filePtr;

// Open a file for writing


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

// Check if the file was opened successfully


if (filePtr == NULL) {
printf("Unable to open the file.\n");
return 1;
}

// Write a character using fputc


fputc('H', filePtr);

// Write a string using fputs


fputs("ello, World!", filePtr);

// Close the file


fclose(filePtr);

printf("Data written to file successfully.\n");

return 0;
}

In this program:
- We first open a file named "output.txt" in write mode using `fopen()`.
- We use `fputc()` to write a single character ('H') to the file.
- We use `fputs()` to write a string ("ello, World!") to the file.
- Finally, we close the file using `fclose()`.
- If the file cannot be opened, we print an error message.

This program illustrates the use of `fputc()` to write individual characters and
`fputs()` to write strings to a file.

Page 30 of 33
Q27) Explain fopen() and fclose() file handling functions.
Ans 27) `fopen()` and `fclose()` are file handling functions commonly used in
programming languages like C and C++. Here's an explanation of each:

1. **fopen() Function**:
- `fopen()` is used to open a file and associate it with a stream, which serves
as a connection between the file and the program.
- Syntax: `FILE *fopen(const char *filename, const char *mode);`
- Parameters:
- `filename`: A string containing the name of the file to be opened.
- `mode`: A string specifying the mode in which the file is to be opened (e.g.,
read mode, write mode, append mode, etc.).
- Return Value:
- If successful, `fopen()` returns a pointer to a `FILE` object that is used to
identify the stream.
- If unsuccessful, it returns `NULL`.

Example:
————————————————————————————————
FILE *fp;
fp = fopen("example.txt", "r"); // Opens a file named "example.txt" in read
mode
if (fp == NULL) {
printf("Error opening file!\n");
exit(1);
}
————————————————————————————————

2. **fclose() Function**:
- `fclose()` is used to close a file stream that was previously opened with
`fopen()`.
- Syntax: `int fclose(FILE *stream);`
- Parameters:
- `stream`: A pointer to the `FILE` object that represents the file stream to be
closed.
- Return Value:
- `fclose()` returns `0` upon successful closing of the file stream.
- It returns `EOF` (End-of-File) if an error occurs while closing the file.

Page 31 of 33
Example:
————————————————————————————————

int result = fclose(fp);


if (result == 0) {
printf("File closed successfully.\n");
} else {
printf("Error closing file!\n");
}
————————————————————————————————
It's essential to properly handle file operations to avoid potential issues such as
file corruption or resource leaks. Therefore, after opening a file using `fopen()`,
it's good practice to close it using `fclose()` once all the necessary operations
have been performed on it.

Q28) Describe file management? Recall various file modes.


Ans 28) File management in computer science refers to the manipulation and
organization of files stored on a computer's filesystem. It involves tasks such as
creating, opening, reading, writing, closing, renaming, deleting, and
manipulating files and directories.

Here are some key aspects of file management:

1. **File Creation**: Creating a new file involves allocating space on the


filesystem and defining its attributes, such as name, size, and type.

2. **Opening and Closing Files**: Files are opened to perform read or write
operations, and they must be closed after use to release system resources.

3. **Reading and Writing Files**: Reading from files involves retrieving data
stored in them, while writing to files involves storing new data or modifying
existing data.

4. **File Modes**: File modes specify the type of access permitted when
opening a file. Common file modes include:
- **"r"**: Open for reading. The file must exist.
- **"w"**: Open for writing. If the file exists, its contents are overwritten. If
the file does not exist, it's created.
- **"a"**: Open for appending. Data is added to the end of the file. If the file
does not exist, it's created.
- **"r+"**: Open for reading and writing. The file must exist.

Page 32 of 33
- **"w+"**: Open for reading and writing. If the file exists, its contents are
overwritten. If the file does not exist, it's created.
- **"a+"**: Open for reading and appending. Data can be read from and
added to the end of the file. If the file does not exist, it's created.

5. **File Positioning**: Files have a current position indicator that determines


the location within the file where read or write operations occur. File
positioning functions like `fseek()` and `rewind()` are used to move the file
position indicator.

6. **Error Handling**: File management functions often return error codes or


set error flags to indicate errors, such as file not found, permission denied, or
disk full.

7. **File Attributes**: Files have attributes such as size, permissions,


timestamps (creation, modification, access), and ownership information (user,
group).

Effective file management is crucial for organizing data, ensuring data integrity,
and optimizing resource usage on computer systems. It involves understanding
and using various file operations and modes effectively to perform tasks
efficiently and securely.

Page 33 of 33

You might also like