0% found this document useful (0 votes)
7 views13 pages

C Programming: Pointers and File Handling

Chapter 5 covers pointers and file handling in C programming, explaining the nature and usage of pointers, types of files, and basic file operations. It discusses random and sequential files, their characteristics, advantages, and disadvantages, as well as functions for reading from and writing to files. Key functions like fopen(), fclose(), fscanf(), and fprintf() are highlighted for file management.

Uploaded by

sonimishra28062
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)
7 views13 pages

C Programming: Pointers and File Handling

Chapter 5 covers pointers and file handling in C programming, explaining the nature and usage of pointers, types of files, and basic file operations. It discusses random and sequential files, their characteristics, advantages, and disadvantages, as well as functions for reading from and writing to files. Key functions like fopen(), fclose(), fscanf(), and fprintf() are highlighted for file management.

Uploaded by

sonimishra28062
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

CHAPTER 5 POINTER AND FILE HANDLING

VERY SHORT ANSWERS

Q.1 Is that possible to add pointer to each other?

Ans. In the C programming language, it is not possible to directly add two pointers to each
other as this operation is considered invalid because the result of adding two memory
addresses is not a meaningful or well-defined memory address.

Q.2 Where is the pointer variable stored in the memory?

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

Q.3 What is a file?

Ans. A File is a collection of data stored in the secondary memory. 23ew

Q.4 What are the main type of files?

Ans. Two

(i)Random Access File (ii)Sequential File

Q.5 Explain any function used to search the file.

Ans. In C, the primary function used to initiate interaction with a file, including "searching" for
its existence and opening it for reading, is “fopen()”.

Q.6 What is the main characteristic of random file?

Ans. Random access allows direct reading or writing of data at any position within a file,
without the need to process preceding data.

Q.7 What is the main characteristic of sequential file?

Ans. The main characteristic of a sequential file in C is that data must be accessed in a linear,
step-by-step manner from the beginning of the file.

Q.8 What is the full form of EOF?

Ans. End-Of-File (It is a condition in a computer operating system where no more data can be
read from a data source.)
SHORT ANSWERS

Q.1 What is the usage of the pointer in C?

Ans. Following are the usage:

 Pointers are used for dynamic memory allocation and deallocation.


 An Array or a structure can be accessed efficiently with pointers
 Pointers are useful for accessing memory locations.
 Pointers are used to form complex data structures such as linked lists, graphs, trees,
etc.
 Pointers reduce the length of the program and its execution time as well.
Q.2 What is an array of pointers?
Ans. In C, a pointer array is a homogeneous collection of indexed pointer variables that are
references to a memory location. It is generally used in C Programming when we want to
point at multiple memory locations of a similar data type in our C program. We can access the
data by dereferencing the pointer pointing to it.
Syntax:
pointer_type *array_name [array_size];
Here,
 pointer_type: Type of data the pointer is pointing to.
 array_name: Name of the array of pointers.
 array_size: Size of the array of pointers.

Q.3 What do you mean by the pointer to a function?


Ans. In C, a function pointer is a type of pointer that stores the address of a function,
allowing functions to be passed as arguments and invoked dynamically. It is useful in
techniques such as callback functions, event-driven programs, and polymorphism (a concept
where a function or operator behaves differently based on the context).

Let's take a look at an example:


#include <stdio.h>

int add(int a, int b) {


return a + b;
}

int main() {
int (*fptr)(int, int);
fptr = &add;
printf("%d", fptr(10, 5));
return 0;
}

In this program, we define a function add(), assigns its address to a function pointer fptr, and
invokes the function through the pointer to print the sum of two integers.
Q.4 How many modes are there to open a file? Explain with example.
Ans. There are the following modes for opening a file:

Q.5 What is File Operation? Explain briefly.


Ans. File operation refers to the actions performed on files, such as creating, reading, writing,
and deleting them. These operations are fundamental for managing data on a computer and
are carried out through system calls that interact with the operating system and file system.

Basic file operations


 Creating a file: Generates a new file, requires finding space on storage, and creates an entry in
the directory.
 Reading a file: Accesses data from an existing file.
 Writing to a file: Stores data into a file.
 Repositioning: Moving to a different location within a file for a subsequent read or write
operation.
 Deleting a file: Permanently removes a file and frees up its storage space.
 Truncating a file: Deletes the contents of a file but leaves the file itself intact.
Q.6 Differentiate between random access files and sequential files.
Ans.
Sequential Memory Access Random Memory Access

Memory access time depends on The amount of time needed to


where the store is located. access memory is not dependent
Sequential Memory Access Random Memory Access

on the storage location.

In Sequential Memory Access, In Random Memory Access,


memory access time is more. memory access time is less.

Sequential Memory Access Random Memory Access having


having non-volatile memory. volatile memory.

Implementation of Sequential Implementation of Random


Memory Access is Memory Access is
straightforward. straightforward.

Example: Semi-conductor
Example: Magnetic tape
devices

LONG ANSWER TYPE QUESTION

Q.1 What is pointer? Mention the advantages of pointer.


Ans. In C programming, a pointer is a variable that stores the memory address of another
variable.
Instead of holding a value directly, a pointer “points” to the location in memory where the
value is stored.
Advantages of pointers:

 Efficient memory management: Pointers allow for dynamic memory allocation and
deallocation, meaning memory can be allocated and released as needed at runtime.
 Faster execution: By directly accessing memory addresses, pointers reduce the need to copy
large amounts of data, leading to faster execution times.
 Dynamic data structures: Pointers are fundamental for building and manipulating dynamic data
structures such as linked lists, trees, stacks, and queues.
 Passing arguments by reference: Pointers enable functions to modify the original variables
passed to them (pass-by-reference), which is more efficient than passing by value, especially for
large data types.
 Returning multiple values from a function: A function can use pointers to return multiple
values by modifying the variables passed by reference.
 Array and string manipulation: Pointers provide an efficient way to work with arrays and
strings in C, allowing for direct access to elements and efficient traversal.
 Memory access and manipulation: Pointers provide a way to access and manipulate data at a
lower level, which is crucial for certain programming tasks, such as interacting with hardware.
Q.2 Distinguish between the Address operator and Derefrencing operator.
Ans. Address Operator (&):

 Purpose:
The address operator, also known as the "address-of" operator or "reference" operator, is used
to obtain the memory address of a variable.
 Usage:
When applied to a variable, it returns the memory location where that variable's value is
stored. This address can then be assigned to a pointer variable.
Example:
int x = 10;
int *ptr_x; // Declare a pointer to an integer
ptr_x = &x; // Assign the address of x to ptr_x
Dereferencing Operator (*):

 Purpose:
The dereferencing operator, also known as the "indirection" operator, is used to access the
value stored at the memory address pointed to by a pointer.
 Usage:
When applied to a pointer variable, it retrieves the data located at the memory address held by
that pointer. This allows you to read or modify the value of the variable the pointer points
to.
Example:
int x = 10;
int *ptr_x;
ptr_x = &x;

printf("%d\n", *ptr_x); // Dereference ptr_x to print the value of x (10)


*ptr_x = 20; // Dereference ptr_x to modify the value of x to 20

Q.3 How do you declare a pointer variable? Explain with example.


Ans. In C, a pointer variable is declared by specifying the data type of the variable it will point
to, followed by an asterisk (*), and then the name of the pointer variable. The asterisk indicates
that the variable being declared is a pointer.

Syntax:
data_type *pointer_name;
Example:
#include <stdio.h>
int main() {
// Declare an integer variable
int num = 10;

// Declare an integer pointer and initialize it with the address of 'num'


int *ptr = &num;

// Print the value of 'num'


printf("Value of num: %d\n", num);

// Print the address of 'num'


printf("Address of num: %p\n", (void*)&num);

// Print the value stored in 'ptr' (which is the address of 'num')


printf("Value of ptr (address of num): %p\n", (void*)ptr);

// Print the value pointed to by 'ptr' (dereferencing the pointer)


printf("Value pointed to by ptr: %d\n", *ptr);

return 0;
}
Q.4 What do you understand by pointer initialization? Explain with example.
Ans. Pointer initialization in C means assigning a valid memory address to a pointer at the
time of declaration or before it is used.
A pointer must contain a meaningful address before dereferencing it; otherwise, it leads to
undefined behavior.

Pointer initialization means giving a pointer:

1. The address of an existing variable, or


2. A valid memory location (like from malloc()), or
3. A NULL value (indicating it points to nothing yet)

Without initialization, a pointer contains garbage (random address), which is dangerous.

Example:

#include <stdio.h>

int main()

int x = 10;
int *p1 = &x; // initialized with address of x

int *p2 = NULL; // initialized to NULL

printf("Value of x using p1: %d\n", *p1);

if (p2 == NULL)

printf("p2 is not pointing to valid memory\n");

return 0;

Q.5 What is a file? How will you open and close a file? Explain input and output operation of
a file.

Ans. A file is a collection of data stored on a storage device such as a hard disk, SSD, or USB
drive. In C programming, a file allows data to be stored permanently and retrieved later.
Files are useful when data must persist even after the program ends.

In C, files are handled using the FILE structure defined in the header:

Opening and Closing a File in C (using pointers):

 Declare a File Pointer:


A FILE pointer, typically declared as FILE *fp;, is used to establish a connection between your
program and the file on the disk. This pointer holds information about the file's state, location,
and access mode.
 Open the File:
The “fopen()” function opens a file and returns a FILE pointer.
Its syntax is:

FILE *fopen(const char *filename, const char *mode);

Example:

FILE *fp;

fp = fopen("[Link]", "w");
if (fp == NULL) {

// Handle error: file could not be opened

 Close the File: The “fclose()” function closes an open file, releasing the resources associated
with it.
Its syntax is:
int fclose(FILE *fp);
Example:
fclose(fp); // Closes the file pointed to by fp
 Input Operations (Reading):

1 . fscanf() — read formatted data


Syntax:

fscanf(fptr, "%d", &num);

2. fgets() — read a string


Syntax:

char line[50];
fgets(line, 50, fptr);

3. fgetc() — read a single character


Syntax:

char ch = fgetc(fptr);
 Output Operations (Writing):

1. fprintf() — write formatted text


Syntax:

fprintf(fptr, "Age = %d", age);

2. fputs() — write a string


Syntax:

fputs("Hello World", fptr);

3. fputc() — write a single character


Syntax:

fputc('A', fptr);
Q.6 Explain the Random Access File and it’s uses.
Ans. A Random Access File (RAF) lets you read/write data at any location directly, like a byte
array with a movable pointer, unlike sequential files needing to read from the start; it's used for
databases, multimedia (MP3, PDF), games, and any application needing fast, direct data
manipulation without reading everything first, enabling efficient updates and precise control.

In C, random access is achieved using the functions:

 fseek() → Move the file pointer to a specific location


 ftell() → Get current position of the file pointer
 frewind() → Move file pointer to the beginning

Uses of Random Access File:


 Databases: Storing records, allowing quick retrieval or updates of specific entries (e.g.,
customer records).
 Multimedia: Handling complex formats like MP3, WAV, or PDF files, where you need to jump to
specific parts (e.g., skipping to a certain time in a song).
 Games: Saving game states, loading levels, or managing in-game assets efficiently.
 Custom File Formats: Building applications that use proprietary data formats, needing precise
byte-level control.
 Indexing: Creating indexes for faster searching within large datasets.

Q.7 Explain the Sequential File and it’s uses, advantages and disadvantages.
Ans. A Sequential File stores data records one after another in a fixed order (like a playlist),
accessed linearly from the beginning, making them great for simple, bulk data tasks (batch
processing, logs, archives) but slow for finding specific records. Uses include payroll, transaction
logs, and report generation where you process everything in order, but not ideal for quick
lookups.
 Uses:

 Batch Processing: Processing large volumes of data at once (e.g., end-of-month billing).
 Transaction Logs: Recording events as they happen (e.g., system activity, financial
transactions).
 Data Archiving: Storing historical data for backup or later analysis.
 Report Generation: Creating reports where all records need to be read in order (e.g., payroll,
student grades).
 Simple Data Storage: Ideal for data that's always accessed in its natural order.
 Advantages:
 Simple & Efficient: Easy to implement and very fast for sequential tasks.
 Cost-Effective Storage: Works well on inexpensive media like magnetic tapes.
 Disadvantages:
 Slow for Random Access: Finding one specific record is time-consuming.
 Costly Updates: Inserting or deleting records in the middle requires rewriting large portions of
the file.

Q.8 Explain the functions used to read from the file.


Ans. Several functions are commonly used to read data from files in programming, particularly
in languages like C. These functions offer different levels of granularity and are suited for
various types of data.

1. Reading Characters:
 fgetc(): Reads a single character from the file stream pointed to by the file pointer. It returns
the character read (as an int) or EOF if the end of the file is reached or an error occurs.
Syntax:
int character = fgetc(filePointer);

 getc(): Similar to fgetc(), but it can be implemented as a macro, potentially offering faster
execution in some cases.
2. Reading Strings/Lines:
 fgets(): Reads a specified number of characters or until a newline character (\n) is encountered,
whichever comes first, into a character array. It also appends a null terminator (\0) to the end
of the string.
Syntax:
char buffer[100];
fgets(buffer, sizeof(buffer), filePointer);

3. Reading Formatted Data:


 fscanf(): Reads formatted input from a file, similar to scanf() for standard input. It uses a format
string to interpret and store data into specified variables.
Syntax:
int number;
char name[50];
fscanf(filePointer, "%d %s", &number, name);

4. Reading Binary Data:


 fread(): Reads a block of data of a specified size and count from a binary file into a memory
location. This is crucial for handling non-textual data.
Syntax:
struct MyData data;
fread(&data, sizeof(struct MyData), 1, filePointer);

5. Reading Integers:
 getw(): Reads an integer from the file. This function is less common in modern C programming
compared to fscanf() or fread() for general integer reading.

Q.9 Explain the functions used to write data in the file.


Ans. To write data to a file in C programming, several functions are available, each designed
for specific data types or formatting needs. All these functions require a file pointer (of
type FILE*) obtained from fopen() in write ("w"), append ("a"), or read/write ("w+", "a+", "r+")
modes.

Here are the primary functions used for writing data to files:
 fprintf(): This function writes formatted output to a file, similar to how printf() writes to the
console. It takes a file pointer, a format string, and a variable number of arguments, allowing
for flexible data output with type conversion.
Syntax:
fprintf(file_pointer, "Format string", arg1, arg2, ...);

 fputs(): This function writes an entire string to a file. It takes the string to be written and the file
pointer as arguments. A newline character is not automatically added by fputs(), so it must be
explicitly included in the string if desired.
Syntax:
fputs(string_to_write, file_pointer);

 fputc(): This function writes a single character to a file. It takes the character to be written and
the file pointer as arguments.
Syntax:
fputc(character_to_write, file_pointer);
 fwrite(): This function writes blocks of raw binary data to a file. It is particularly useful when
dealing with structures or other binary data where direct memory copies are efficient. It takes a
pointer to the data, the size of each element, the number of elements, and the file pointer.
Syntax:
fwrite(data_pointer, size_of_element, number_of_elements, file_pointer);

 fputw(): This function writes an integer to a file. While less common than fprintf() for general
integer writing, it can be used for this specific purpose.
Syntax:
fputw(integer_value, file_pointer);

After writing operations are complete, it is crucial to close the file using “fclose(file_pointer)” to
ensure all buffered data is written to disk and resources are released.

Q.10 Explain following functions:


(a) fopen():
The fopen() function is a standard library function in C (and similar functions exist in
other languages like PHP) used for opening files and associating a stream with them. It returns a
pointer to a FILE object (or a resource in PHP) that can then be used by other file handling
functions to perform operations like reading from or writing to the file.

Syntax :
FILE *fopen(const char *filename, const char *mode);

(b) feof() :

It is a function (common in C) that checks a file stream's End-Of-File (EOF) indicator,


returning non-zero (true) if the indicator is set (meaning a read attempt went past the actual
end), and zero (false) otherwise, helping programs detect when to stop reading from a file. It's
crucial for robust file handling, but should typically be used with ferror() in a loop,
as feof() only flags after an unsuccessful read, not before.

The value of EOF is implementation-defined, but generally is -1.

Syntax:

int feof(FILE *fp);

(c) fseek() :

The fseek() function is used to move the file pointer to a specific position in a file.
It is mainly used in random access files, where you can directly jump to any location without
reading the entire file.
Syntax:
int fseek(FILE *fp, long offset, int origin);

(d) rewind() :
The rewind() function is used to “move the file pointer back to the beginning of
the file.”
Its primary purpose is to reposition the file position indicator (also known as the file pointer)
to the beginning of the specified file stream.

It is essentially a shortcut for:

fseek(fp, 0, SEEK_SET);
Syntax:
void rewind(FILE *stream);

rewind() is commonly used when you need to process a file multiple times from the beginning
without closing and reopening it. For example, you might read data from a file, then
use rewind() to return to the start and read it again for a different purpose, or to write new
data to the beginning.

You might also like