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

pcl pyq(unit3)

The document provides an in-depth explanation of pointers, structures, and unions in C programming. It covers topics such as pointer declaration and initialization, chain of pointers, pointer arithmetic, and accessing arrays with pointers, as well as the definitions and examples of structures and unions. Additionally, it discusses how to pass structures to functions, the concept of nested structures, and arrays of structures.

Uploaded by

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

pcl pyq(unit3)

The document provides an in-depth explanation of pointers, structures, and unions in C programming. It covers topics such as pointer declaration and initialization, chain of pointers, pointer arithmetic, and accessing arrays with pointers, as well as the definitions and examples of structures and unions. Additionally, it discusses how to pass structures to functions, the concept of nested structures, and arrays of structures.

Uploaded by

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

UNIT-3(POINTERS,STRUCTURES & UNIONS,FILE

HANDLING)
POINTERS

1Q. What is a Pointer? How do you declare and initialize it?


Ans. A pointer in C is a variable that stores the memory address of another variable. It
provides a way to indirectly access and manipulate data stored in memory.

Declaring a Pointer:

To declare a pointer, you use the * operator. The syntax is:

data_type *pointer_name;

Here, data_type specifies the data type of the variable whose address the pointer will hold.

Example:

int *ptr;

This declaration creates a pointer named ptr that can hold the address of an integer variable.

Initializing a Pointer:

There are two common ways to initialize a pointer:

1. Assigning the Address of a Variable:


You can assign the address of an existing variable to a pointer using the & operator.
This operator gives the address of the variable.

int x = 10;
int *ptr = &x;

Now, ptr holds the memory address of x.


2. Directly Assigning a Memory Address:
While less common, you can directly assign a memory address to a pointer using the
malloc() function. This function allocates memory dynamically.

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

This allocates memory for an integer and assigns its address to ptr.
Accessing the Value Pointed to by a Pointer:

To access the value stored at the memory location pointed to by a pointer, you use the *
operator again, but in a different context.

int value = *ptr;

2Q. Explain the concept of Chain of Pointers with example.


Ans. A chain of pointers in C refers to a series of pointers where each pointer stores the
memory address of another pointer, creating multiple levels of indirection.
Understanding Levels:

• A normal pointer (int *ptr) points to the address of an integer variable.


• A double pointer (int **ptrptr) points to the address of another pointer, which ultimately
points to an integer variable.
• You can have even more levels, like triple pointers (int ***ptrptrptr) and so on.
Example: Modifying a Variable Through a Chain of Pointers

Here's an example demonstrating how to modify a variable through a chain of pointers:

#include <stdio.h>

int main() {
int value = 10; // Original variable

// Declare a chain of pointers


int *ptr, **ptrptr, ***ptrptrptr;

// Assign address of 'value' to the first pointer


ptr = &value;

// Assign address of 'ptr' to the double pointer


ptrptr = &ptr;

// Assign address of 'ptrptr' to the triple pointer


ptrptrptr = &ptrptr;

// Modify value using the triple pointer (3 levels of indirection)


*(*(*ptrptrptr)) = 20; // Equivalent to *ptr = 20;

printf("Original value: %d\n", value); // Prints 20 (modified)

return 0;
}

3Q. Briefly explain pointer arithmetic.


Ans. Pointer arithmetic refers to the set of valid arithmetic operations that can be performed
on pointers in C. These operations differ slightly from regular arithmetic as pointers store
memory addresses.

Key Points:

• Addition/Subtraction of Integers:
Adding an integer to a pointer moves it forward in memory by a specific number of
o
elements.
o Subtracting an integer moves it backward.
o The amount of movement depends on the size of the data type the pointer points to.
(e.g., adding 1 to an integer pointer moves it 4 bytes if an integer is 4 bytes)
• Comparison of Pointers:
o You can compare pointers using relational operators (==, <, >) only if they point to
elements within the same array or memory block allocated with malloc.
o Comparing pointers from different memory areas is meaningless.
Example:

int numbers[] = {10, 20, 30, 40, 50};


int *ptr = numbers; // ptr points to the first element (10)

ptr++; // Move ptr to the second element (20)


printf("%d\n", *ptr); // Prints 20 (dereference to access value)

ptr += 2; // Move ptr 2 elements forward (40)


printf("%d\n", ptr - numbers); // Prints 2 (distance between
pointers in elements)

4Q. Explain the concept of pointer to array with example.


Ans. A pointer to an array is a variable that stores the memory address of an entire array.
Unlike a normal pointer that points to a single element, a pointer to an array points to the
base address of the array, which is the memory address of the first element.

Declaration:

data_type (*ptr)[size];

Here:

• data_type: The data type of the elements in the array.


• ptr: The name of the pointer variable.
• size: The size of the array.
Example:

#include <stdio.h>

int main() {
int arr[5] = {10, 20, 30, 40, 50};
int (*ptr)[5]; // Pointer to an array of 5 integers

ptr = &arr; // Assign the address of the array to the pointer

// Accessing elements using the pointer


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

return 0;
}

5Q. How do we access 1D and 2D array using pointers.


Ans. 1. Accessing 1D Arrays with Pointers
In C, an array name itself decays to a pointer to its first element. This means you can use
array notation (arr[i]) and pointer notation (*(arr + i)) interchangeably to access elements.

Example:

#include <stdio.h>

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

// Accessing elements using array notation


printf("numbers[2]: %d\n", numbers[2]); // Prints 30

// Accessing elements using pointer notation


int *ptr = numbers; // ptr now points to the first element (10)
printf("*(ptr + 1): %d\n", *(ptr + 1)); // Prints 20

// Looping through the array using a pointer


for (int i = 0; i < 5; i++) {
printf("%d ", *(ptr + i));
}

return 0;
}

2. Accessing 2D Arrays with Pointers

Example:

#include <stdio.h>

int main() {
int matrix[3][4] = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11,
12}};

int (*ptr)[4] = matrix; // ptr points to the first row

// Accessing elements using pointer notation and array indexing


printf("matrix[1][2]: %d\n", matrix[1][2]); // Prints 7
printf("*(ptr + 1)[2]: %d\n", *(ptr + 1)[2]); // Prints 7
(equivalent)

// Looping through rows and columns using pointer arithmetic


for (int i = 0; i < 3; i++) {
for (int j = 0; j < 4; j++) {
printf("%d ", *((ptr + i) + j)); // Double dereference
to access element
}
printf("\n");
}

return 0;
}
6Q. Explain (a)Void/Generic pointer (b)
Ans.(a) A void pointer, declared as void *, is a special type of pointer that can point to any
data type. It doesn't have a specific type associated with it, making it highly flexible but
requiring careful handling.

Declaration:

void *ptr;

Assigning Values:

You can assign the address of any variable to a void pointer, regardless of its data type.
However, to access the value stored at the address, you need to cast the void pointer to the
appropriate data type.

Example:

#include <stdio.h>

int main() {
int num = 10;
char ch = 'A';
float f = 3.14;

void *ptr;

ptr = &num; // Assigning address of an integer


printf("Integer value: %d\n", *(int *)ptr);

ptr = &ch; // Assigning address of a character


printf("Character value: %c\n", *(char *)ptr);

ptr = &f; // Assigning address of a float


printf("Float value: %f\n", *(float *)ptr);

return 0;
}

(b) The * Operator: Dereference Operator

• Purpose: Used to access the value stored at a memory location pointed to by a pointer.
• Syntax: *pointer_name
Example:

int x = 10;
int *ptr = &x; // ptr stores the address of x

printf("%d\n", *ptr); // Prints 10 (value at the address stored in


ptr)
The & Operator: Address-of Operator

• Purpose: Used to get the memory address of a variable.


• Syntax: &variable_name
Example:

int x = 10;
int *ptr = &x; // ptr stores the address of x

printf("%p\n", ptr); // Prints the memory address of x

STRUCTURES & UNIONS

1Q. What do you mean by Structures? Explain with code.

Ans. In C, a structure (often shortened to struct) is a user-defined data type that groups
together variables of different data types under a single name. This allows you to create
complex data objects that represent real-world entities or concepts.

Benefits of Structures:

• Data Organization: Structures help organize related data into a single unit, improving
code readability and maintainability.
• Data Packing: You can group variables of different sizes efficiently in memory since C
doesn't have automatic memory padding like some other languages.
Declaring a Structure:

The struct keyword is used to define a structure. You specify a structure name and a list of
member variables enclosed within curly braces {}.

Example:

struct Person {
char name[50]; // Character array to store name
int age; // Integer to store age
float salary; // Float to store salary
};

2Q. What do you mean by Union? Explain with code


Ans. A union is a user-defined data type that allows you to store different data types in the
same memory location. Unlike a structure, where each member has its own memory 1

allocation, a union allocates memory for the largest member and all other members share
this memory space.
Declaration:

The syntax for declaring a union is similar to that of a structure:

union UnionName {
data_type1 member1;
data_type2 member2;
// ...
};

Example:

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

How it Works:

• All members of a union share the same memory location.


• When you assign a value to one member, the values of other members become
undefined.
• The size of a union is equal to the size of its largest member.
Example

#include <stdio.h>

int main() {
union Data data;

data.i = 10;
printf("Integer value: %d\n", data.i);

data.f = 220.5;
printf("Float value: %f\n", data.f);

strcpy(data.str, "C Programming");


printf("String value: %s\n", data.str);

return 0;
}

3Q. How do we pass structure to a function?


Ans. There are two primary ways to pass a structure to a function in C:

1. Pass by Value:

In this method, a copy of the entire structure is passed to the function. Any modifications
1

made to the structure within the function will not affect the original structure in the calling
function.2
#include <stdio.h>

struct Student {
char name[50];
int age;
float marks;
};

void printStudentDetails(struct Student s) {


printf("Name: %s\n", s.name);
printf("Age: %d\n", s.age);
printf("Marks: %.2f\n", s.marks);
}

int main() {
struct Student student1 = {"Alice", 20, 95.5};
printStudentDetails(student1);
return 0;
}

2. Pass by Reference:

In this method, the address of the structure is passed to the function. This allows the
function to modify the original structure directly.

#include <stdio.h>

struct Student {
char name[50];
int age;
float marks;
};

void printStudentDetails(struct Student *s) {


printf("Name: %s\n", s->name);
printf("Age: %d\n", s->age);
printf("Marks: %.2f\n", s->marks);
}

int main() {
struct Student student1 = {"Alice", 20, 95.5};
printStudentDetails(&student1);
return 0;
}

4Q. Briefly explain Pointer to Structure.


Ans. A pointer to structure in C is a variable that stores the memory address of a structure. It
allows you to work with structures indirectly, providing several advantages:

Benefits:

• Efficient Function Argument Passing: Passing structures by reference (using pointers)


avoids copying the entire structure, improving efficiency for large structures.
• Dynamic Memory Allocation: Pointers to structures can be used with malloc and free to
allocate and deallocate memory for structures dynamically, creating flexible data
structures like linked lists and trees.
• Modifying Structures within Functions: Pointers let you modify structure members
directly within functions.
Declaration:

data_type *ptr_name;

Here:

• data_type: The data type of the structure the pointer points to.
• ptr_name: The name of the pointer variable.
Example:

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

int main() {
struct Student student1 = {"Alice", 20};
struct Student *ptr; // Pointer to a Student structure

ptr = &student1; // Assign address of student1 to ptr

// Access and modify structure members using the pointer


printf("Original name: %s\n", ptr->name); // Access using ->
operator
strcpy(ptr->name, "Bob"); // Modify name through the pointer
printf("Modified name: %s\n", ptr->name);

return 0;
}

5Q. Write short note on structure within structure/ nested structure.


Ans. A nested structure is a structure that contains another structure as one of its members.
This allows you to create hierarchical data structures, representing more complex
relationships between data.

Example:

struct Address {
char street[50];
char city[30];
char state[20];
int pincode;
};

struct Student {
char name[50];
int roll_no;
struct Address address; // Nested structure};
In this example:
• struct Address defines a structure to hold address information.
• struct Student defines a structure to hold student information, including an Address
structure as a member.
Accessing Members of Nested Structures:

To access members of a nested structure, you use the dot (.) operator multiple times:

struct Student s1;

// Assigning values to nested structure members


strcpy(s1.name, "Alice");
s1.roll_no = 10;
strcpy(s1.address.street, "Main Street");
strcpy(s1.address.city, "Cityville");
strcpy(s1.address.state, "Stateville");
s1.address.pincode = 12345;

// Accessing nested members


printf("Student Name: %s\n", s1.name);
printf("Student Address:\n");
printf(" Street: %s\n", s1.address.street);
printf(" City: %s\n", s1.address.city);
printf(" State: %s\n", s1.address.state);
printf(" Pincode: %d\n", s1.address.pincode);

6Q. Write short note on array of structures.


Ans. An array of structures is a collection of structures, where each element of the array is a
structure variable. This allows you to store multiple instances of the same structure type in a
single array.

Declaration:

struct StructureName array_name[size];

Here:

• StructureName: The name of the structure.


• array_name: The name of the array.
• size: The number of elements in the array.
Example:

struct Student {
char name[50];
int roll_no;
float marks;
};

int main() {
struct Student students[3]; // Array of 3 Student structures
// Assign values to the first student
strcpy(students[0].name, "Alice");
students[0].roll_no = 10;
students[0].marks = 95.5;

// Assign values to the second student


strcpy(students[1].name, "Bob");
students[1].roll_no = 20;
students[1].marks = 88.2;

// Access and print information about the first student


printf("Student Name: %s\n", students[0].name);
printf("Roll No: %d\n", students[0].roll_no);
printf("Marks: %.2f\n", students[0].marks);

return 0;
}

7Q. Write short note on array within structure.


Ans. An array within a structure allows you to store multiple elements of the same data type
as a member of the structure. This is useful for representing collections of data within a
single structure.

Example:

struct Student {
char name[50];
int roll_no;
int marks[5]; // Array of 5 marks
};

int main() {
struct Student student1;

strcpy(student1.name, "Alice");
student1.roll_no = 10;
student1.marks[0] = 85;
student1.marks[1] = 92;
// ... and so on

// Accessing and printing marks


printf("Marks: ");
for (int i = 0; i < 5; i++) {
printf("%d ", student1.marks[i]);
}
printf("\n");

return 0;
}
8Q. Differentiation
➢ Structure Vs Union
➢ Array Vs Structure
Ans.
(a)

Feature Structure Union

Memory Each member has its All members share the same memory
Allocation own memory allocation. location.

Size Size is the sum of the Size is equal to the size of its largest
sizes of its members. member.

Accessing Members can be Only one member can be active at a


Members accessed time. Accessing a different member
independently. overwrites the previous value.

Use Cases Organizing related data Storing different data types in the same
into a single unit. memory location, but only one at a
time.

(b)

Feature Array Structure

Definition A collection of elements of A user-defined data type that


the same data type groups variables of different data
types

Memory Contiguous memory Memory allocation for each


Allocation allocation member separately

Accessing Using index Using dot (.) operator


Elements

Flexibility Less flexible, can only store More flexible, can store elements
elements of the same type of different types
Feature Array Structure

Organization Less organized, simple More organized, groups related


collection of elements data together

Real-world A list of numbers or names A person's information (name,


analogy age, address)

FILE HANDLING

1Q. Explain the concept of files in detail. Why do we need files?


Ans. In C, files are essentially named collections of data stored on secondary storage
devices like hard disks or SSDs. They provide a persistent way to store information beyond
the runtime of a program.

Why Do We Need Files in C?

1. Data Persistence:
o Files allow us to save data even after the program terminates. This is crucial for
1

applications that need to store information for future use, such as user preferences,
game progress, or financial records.
2. Data Sharing:
o Files can be easily shared and transferred between different systems, enabling
collaboration and data exchange.
3. Efficient Data Handling:
o By storing large amounts of data in files, we can avoid the need to re-enter it each
time the program runs. This saves time and effort, especially for repetitive tasks.
2

4. Modular Program Design:


o We can separate different parts of a program into different files, making the code
more organized, reusable, and easier to maintain. 3

File Handling in C

2Q. Explain different operations possible on files.


Ans. C provides a set of standard library functions for working with files:4

1. Opening a File:

• fopen() function is used to open a file. It takes two arguments: the filename and the mode
of opening.
FILE *fp = fopen("myfile.txt", "r"); // Open for reading

• The FILE pointer (fp) is used to reference the file.


2. Reading from a File:
• fgetc(), fscanf(), and fgets() functions are used to read data from a file.
char ch;
while ((ch = fgetc(fp)) != EOF) {
putchar(ch);
}

3. Writing to a File:

• fputc(), fprintf(), and fputs() functions are used to write data to a file.

fprintf(fp, "This is a line of text.\n");

4. Closing a File:

• fclose() function is used to close a file.


fclose(fp);

3Q. Briefly explain various file opening modes.

Ans. Read Modes:

• "r": Opens a file for reading. If the file doesn't exist, the function returns NULL. This
mode is for existing files you want to read from.
• "rb": Opens a file for reading in binary mode. Similar to "r", but treats the file as a
stream of bytes (important for non-text files).

Write Modes:

• "w": Creates a new file for writing. If the file exists, its content is overwritten. Use
this to create a new file or completely rewrite an existing one.
• "wb": Creates a new file for writing in binary mode. Similar to "w", but for binary
data.

Append Modes:

• "a": Opens a file for appending. If the file doesn't exist, it creates a new one. Data is
written to the end of the file. Use this to add content to an existing file without
overwriting it.
• "ab": Opens a file for appending in binary mode. Similar to "a", but for binary data.

Read-Write Modes:

• "r+": Opens an existing file for both reading and writing. If the file doesn't exist, the
function returns NULL. Use this for existing files where you might need to read and
modify content.
• "rb+": Opens an existing file for both reading and writing in binary mode. Similar to
"r+", but for binary data.
• "w+": Creates a new file for both reading and writing. If the file exists, its content is
overwritten. Use this to create a new file or completely rewrite an existing one,
allowing both read and write access.
• "wb+": Creates a new file for both reading and writing in binary mode. Similar to
"w+", but for binary data.
• "a+": Opens an existing file for both reading and appending. If the file doesn't exist,
it creates a new one. Data is written to the end of the file, allowing both reading and
appending.
• "ab+": Opens an existing file for both reading and appending in binary mode. Similar
to "a+", but for binary data.

4Q. Explain the concept of Reading and Writing using Character I/O Functions with
example.
Ans. 1. Reading Characters:

• getchar() function:
o Reads a single character from the standard input (usually keyboard). 1

o Returns the character as an int (ASCII value) or EOF on end-of-file.

char ch = getchar();
printf("You entered: %c\n", ch);

• getc() function:
o Similar to getchar(), but takes a file pointer as an argument.
o Reads a character from the specified file stream. 2

o Returns the character read or EOF on end-of-file.

FILE *fp = fopen("myfile.txt", "r");


if (fp != NULL) {
char ch;
while ((ch = getc(fp)) != EOF) {
putchar(ch);
}
fclose(fp);
} else {
printf("Error opening file!\n");
}

2. Writing Characters:

• putchar() function:
o Writes a single character to the standard output (usually console). 3

o Takes the character as an int (ASCII value).

char ch = 'A';
putchar(ch); // Prints 'A' to the console

• putc() function:
o Similar to putchar(), but takes a file pointer as an argument.
o Writes a character to the specified file stream.
o Takes the character as an int (ASCII value).

FILE *fp = fopen("output.txt", "w");


if (fp != NULL) {
char ch = 'B';
putc(ch, fp);
fclose(fp);
} else {
printf("Error opening file!\n");
}

5Q. Explain the concept of Reading and Writing using String I/O Functions
Ans. 1. Reading Strings:

• gets() function:
o Reads a string from the standard input (usually the keyboard).
o Stores the string in a character array.
o Note: This function is deprecated due to security vulnerabilities. It's recommended to
use safer alternatives like fgets().
char str[100];
printf("Enter a string: ");
gets(str);
printf("You entered: %s\n", str);

• fgets() function:
o Reads a line of text from a file or standard input.
o Takes a character array, maximum number of characters to read, and a file pointer as
arguments.
o Returns the string read or NULL on error or end-of-file.
char str[100];
printf("Enter a string: ");
fgets(str, 100, stdin);
printf("You entered: %s\n", str);

2. Writing Strings:

• puts() function:
o Writes a string to the standard output (usually the console), followed by a newline
character.
o Takes a string as an argument.
char str[] = "Hello, world!";
puts(str);

• fputs() function:
o Writes a string to a file.
o Takes a string and a file pointer as arguments.
FILE *fp = fopen("output.txt", "w");
if (fp != NULL) {
char str[] = "This is a line of text.";
fputs(str, fp);
fclose(fp);
} else {
printf("Error opening file!\n");
}

6Q. Explain the concept of Reading and Writing using integer I/O Functions.
Ans.

1. Reading Integers:

• scanf() function:
o Reads formatted input from the standard input (usually the keyboard).
o Takes a format specifier and a pointer to the variable where the input will be stored.
o For integers, use the %d format specifier.

int num;
printf("Enter an integer: ");
scanf("%d", &num);
printf("You entered: %d\n", num);

• fscanf() function:
o Reads formatted input from a file.
o Similar to scanf(), but takes a file pointer as an additional argument.

FILE *fp = fopen("input.txt", "r");


if (fp != NULL) {
int num;
fscanf(fp, "%d", &num);
printf("Read from file: %d\n", num);
fclose(fp);
} else {
printf("Error opening file!\n");
}

2. Writing Integers:

• printf() function:
o Prints formatted output to the standard output (usually the console).
o Takes a format specifier and the value to be printed.
o For integers, use the %d format specifier.

int num = 42;


printf("The number is: %d\n", num);

• fprintf() function:
o Writes formatted output to a file.
o Similar to printf(), but takes a file pointer as an additional argument.
FILE *fp = fopen("output.txt", "w");
if (fp != NULL) {
int num = 123;
fprintf(fp, "The number is: %d\n", num);
fclose(fp);
} else {
printf("Error opening file!\n");
}

7Q. Explain the concept of Reading and Writing using formatted I/O Functions.
Ans. 1. Reading Formatted Input:

• scanf() function:
o Reads formatted input from the standard input (usually the keyboard).
o Takes a format string and pointers to variables where the input will be stored.
o The format string specifies the expected input format using format specifiers.

int age;
float salary;
char name[50];

printf("Enter your age, salary, and name: ");


scanf("%d %f %s", &age, &salary, name);

printf("Age: %d\nSalary: %.2f\nName: %s\n", age, salary, name);

2. Writing Formatted Output:

• printf() function:
o Prints formatted output to the standard output (usually the console).
o Takes a format string and values to be printed.
o The format string specifies how the values should be formatted.

int num = 42;


float pi = 3.14159;
char str[] = "Hello, world!";

printf("Integer: %d\nFloat: %.2f\nString: %s\n", num, pi, str);

Common Format Specifiers:

• %d: Integer
• %f: Floating-point number
• %c: Character
• %s: String
• %x: Hexadecimal integer
• %o: Octal integer
8Q. Explain the concept of Reading and Writing using Unformatted I/O Functions.
Ans. 1. Reading Characters:

• getchar() function:
o Reads a single character from the standard input (usually the keyboard).
o Returns the character as an int (ASCII value) or EOF on end-of-file.

char ch = getchar();
printf("You entered: %c\n", ch);

• getc() function:
o Similar to getchar(), but takes a file pointer as an argument.
o Reads a single character from the specified file stream.
o Returns the character read or EOF on end-of-file or error.

FILE *fp = fopen("myfile.txt", "r");


if (fp != NULL) {
char ch;
while ((ch = getc(fp)) != EOF) {
putchar(ch);
}
fclose(fp);
} else {
printf("Error opening file!\n");
}

2. Writing Characters:

• putchar() function:
o Writes a single character to the standard output (usually the console).
o Takes the character as an int (ASCII value).

char ch = 'A';
putchar(ch); // Prints 'A' to the console

• putc() function:
o Similar to putchar(), but takes a file pointer as an argument.
o Writes a single character to the specified file stream.
o Takes the character as an int (ASCII value).

FILE *fp = fopen("output.txt", "w");


if (fp != NULL) {
char ch = 'B';
putc(ch, fp);
fclose(fp);
} else {
printf("Error opening file!\n");
}
9Q. Explain the concept of File status functions
Ans. File status functions in C provide information about the state of a file. These functions
are essential for error handling, file management, and ensuring proper file operations.

Here are some of the key file status functions:

1. feof():

• Checks if the end-of-file indicator is set for a given file stream.


• Returns a non-zero value if the end-of-file has been reached, otherwise 0.
• It's commonly used in loops to read data from a file until the end is reached.
while (!feof(fp)) {
// Read data from the file
}

2. ferror():

• Checks if an error occurred during a file operation on a given file stream.


• Returns a non-zero value if an error occurred, otherwise 0.
• It's crucial for error handling and debugging.
if (ferror(fp)) {
perror("Error reading file");
exit(1);
}

3. clearerr():

• Clears the error indicator for a given file stream.


• This can be useful if you want to retry a failed operation after taking corrective action.
clearerr(fp);

4. fseek():

• Positions the file pointer to a specific location within a file.


• Takes three arguments: a file pointer, an offset, and a reference point.
• The reference point can be SEEK_SET (beginning of the file), SEEK_CUR (current
position), or SEEK_END (end of the file).
fseek(fp, 10, SEEK_SET); // Move the pointer to the 11th byte

5. ftell():

• Returns the current position of the file pointer.


• This is useful for determining the size of a file or for saving the current position and
returning to it later.

long current_position = ftell(fp);


10Q. Explain the concept of File positioning functions
Ans. File positioning functions in C allow you to manipulate the position of the file pointer
within a file stream. This enables you to read and write data at specific locations within the
file.

Here are the key file positioning functions:

1. fseek():

• Moves the file pointer to a specific position within a file.


• Takes three arguments:
o A file pointer.
o An offset, which is the number of bytes to move.
o A reference point, which can be one of the following:
§ SEEK_SET: Beginning of the file
§ SEEK_CUR: Current position of the file pointer
§ SEEK_END: End of the file
Example:

fseek(fp, 10, SEEK_SET); // Move the pointer to the 11th byte

2. ftell():

• Returns the current position of the file pointer, measured in bytes from the beginning of
the file.
• This can be useful for saving the current position and returning to it later, or for
determining the size of a file.
Example:

long current_position = ftell(fp);

3. rewind():

• Moves the file pointer to the beginning of the file.


• It's a simpler way to reset the file pointer to the start.
Example:

rewind(fp);

11Q.Explain ➢ Header File ➢ File Pointer➢ EOF

Ans.(a) Header Files: Header files in C are files with the .h extension that contain function
declarations, macro definitions, and variable declarations. They are used to share code and
definitions between different source files in a C program.

(b) File Pointer: A file pointer in C is a variable that points to a file. It is used to perform file
operations like reading, writing, and seeking.
(c) EOF (End-of-File)

In C programming, EOF is a special constant that represents the end-of-file condition. It's
often used in file input operations to determine when the end of a file has been reached.

12Q. Differentiation
➢ Stream oriented Vs System oriented data files
➢ Text file Vs Binary file
➢ fputc() vs fgetc()
➢ fputs() vs fgets()
➢ fprintf() vs fscanf()
➢ argc Vs argv[]

Ans.(a)

Feature Stream-Oriented Data Files System-Oriented Data Files

Data Sequential Record-based


Organization

Data Format Textual (ASCII) Binary

I/O Operations Character-based (e.g., Record-based (e.g., fread,


fgetc, fputc) fwrite)

Efficiency Less efficient for large data More efficient for large data

Portability More portable across Less portable across different


different systems systems

Common Reading/writing text, simple Reading/writing complex data


Operations data structures structures, binary data

Example fopen, fclose, fgetc, fputc, fopen, fclose, fread, fwrite


Functions fscanf, fprintf
(b)

Feature Text File Binary File

Data Storage Human-readable characters Raw bytes

File Extension .txt, .c, .h, etc. .bin, .exe, .jpg, etc.

Reading/Writing fgets(), fputs(), fscanf(), fread(), fwrite()


Functions fprintf()

Efficiency Less efficient for large data More efficient for large data

Portability More portable across Less portable, may require


different systems specific system-dependent
handling

Security Less secure, as content can More secure, as content is


be easily viewed and not easily readable
modified

(c)

Feature fputc() fgetc()

Purpose Writes a single character to a Reads a single character from a


file file

Parameters Character to write, file pointer File pointer

Return Character written on Character read on success, EOF


Value success, EOF on error on error or end-of-file

Operation Writes a character to the Reads a character from the


specified file stream specified file stream
(d)

Feature fputs() fgets()

Purpose Writes a string to a file Reads a string from a file

Parameters (const char *str, FILE (char *str, int size, FILE *stream)
*stream)

Return Value Non-zero on success, The string read, or NULL on error


EOF on error or end-of-file

String Appends a newline Does not append a newline


Termination character character

Input/Output Output Input

(e)

Feature fprintf() fscanf()

Purpose Writes formatted output to a Reads formatted input from a file


file

Arguments File pointer, format string, and File pointer, format string, and
values to be printed pointers to variables to store input

Return Number of characters written, Number of items successfully read,


Value or negative value on error or EOF on end-of-file or error

Example fprintf(fp, "Value: %d\n", fscanf(fp, "%d %f", &int_var,


value); &float_var);
(f)

Feature argc argv[]

Type Integer Array of character pointers

Purpose Stores the number of Stores the actual command-line


command-line arguments arguments

Access Directly accessed as an Accessed using array indexing


integer

Example int main(int argc, char argv[0] stores the program name, argv[1]
*argv[]) stores the first argument, and so on.

You might also like