Sunteți pe pagina 1din 20

UNIT-5 Pointers & File handling

Short Answer Type Questions


1. What is Pointer in C programming?

Pointers in C language is a variable that stores/points the address of another


variable. A Pointer in C is used to allocate memory dynamically i.e. at run
time. The pointer variable might be belonging to any of the data type such as int,
float, char, double, short etc.
Pointer Syntax : data_type *var_name; Example : int *p; char *p;
Where, * is used to denote that “p” is pointer variable and not a normal variable.
Key points to remember about pointers in c:
 Normal variable stores the value whereas pointer variable stores the address
of the variable.
 The content of the C pointer always be a whole number i.e. address.
 Always C pointer is initialized to null, i.e. int *p = null.
 The value of null pointer is 0.
 & symbol is used to get the address of the variable.
 * symbol is used to get the value of the variable that the pointer is pointing
to.
 If a pointer in C is assigned to NULL, it means it is pointing to nothing.
 Two pointers can be subtracted to know how many elements are available
between these two pointers.
 But, Pointer addition, multiplication, division are not allowed.
 The size of any pointer is 2 byte (for 16 bit compiler).

#include <stdio.h>
int main()
{
int *ptr, q;
q = 50;
/* address of q is assigned to ptr */
ptr = &q;
/* display q's value using ptr variable */
printf("%d", *ptr);
return 0;
}

2. What is a structure pointer?

C structure can be accessed in 2 ways in a C program. They are,

1. Using normal structure variable


2. Using pointer variable
Dot(.) operator is used to access the data using normal structure variable and arrow
(->) is used to access the data using pointer variable. You have learnt how to access
structure data using normal variable in C – Structure topic. So, we are showing here
how to access structure data using pointer variable in below C program.
Example program for c structure using pointer:
In this program, “record1” is normal structure variable and “ptr” is pointer structure
variable. As you know, Dot(.) operator is used to access the data using normal
structure variable and arrow(->) is used to access data using pointer variable.

#include <stdio.h>
#include <string.h>

struct student
{
int id;
char name[30];
float percentage;
};

int main()
{
int i;
struct student record1 = {1, "Raju", 90.5};
struct student *ptr;
ptr = &record1;

printf("Records of STUDENT1: \n");


printf(" Id is: %d \n", ptr->id);
printf(" Name is: %s \n", ptr->name);
printf(" Percentage is: %f \n\n", ptr->percentage);

return 0;
}

3. What do you understand by self-referential structure?

Self Referential structures are those structures that have one or more pointers which
point to the same type of structure, as their member.

In other words, structures pointing to the same type of structures are self-referential
in nature.

struct node
{
int data1;
char data2;
struct node* link;
};

int main()
{
struct node ob;
return 0;
}

Types of Self Referential Structures


1. Self Referential Structure with Single Link
2. Self Referential Structure with Multiple Links
Self Referential Structure with Single Link: These structures can have only one
self-pointer as their member. The following example will show us how to connect the
objects of a self-referential structure with the single link and access the
corresponding data members.

#include <stdio.h>

struct node {
int data1;
char data2;
struct node* link;
};

int main()
{
struct node ob1; // Node1
// Initialization
ob1.link = NULL;
ob1.data1 = 10;
ob1.data2 = 20;

struct node ob2; // Node2

// Initialization
ob2.link = NULL;
ob2.data1 = 30;
ob2.data2 = 40;

// Linking ob1 and ob2


ob1.link = &ob2;

// Accessing data members of ob2 using ob1


printf("%d", ob1.link->data1);
printf("\n%d", ob1.link->data2);
return 0;
}
Self Referential Structure with Multiple Links: Self referential structures with
multiple links can have more than one self-pointers. Many complicated data
structures can be easily constructed using these structures. Such structures can
easily connect to more than one nodes at a time. The following example shows one
such structure with more than one links.

#include <stdio.h>
struct node {
int data;
struct node* prev_link;
struct node* next_link;
};

int main()
{
struct node ob1; // Node1

// Initialization
ob1.prev_link = NULL;
ob1.next_link = NULL;
ob1.data = 10;

struct node ob2; // Node2

// Initialization
ob2.prev_link = NULL;
ob2.next_link = NULL;
ob2.data = 20;

struct node ob3; // Node3

// Initialization
ob3.prev_link = NULL;
ob3.next_link = NULL;
ob3.data = 30;

// Forward links
ob1.next_link = &ob2;
ob2.next_link = &ob3;
// Backward links
ob2.prev_link = &ob1;
ob3.prev_link = &ob2;

// Accessing data of ob1, ob2 and ob3 by ob1


printf("%d\t", ob1.data);
printf("%d\t", ob1.next_link->data);
printf("%d\n", ob1.next_link->next_link->data);

// Accessing data of ob1, ob2 and ob3 by ob2


printf("%d\t", ob2.prev_link->data);
printf("%d\t", ob2.data);
printf("%d\n", ob2.next_link->data);

// Accessing data of ob1, ob2 and ob3 by ob3


printf("%d\t", ob3.prev_link->prev_link->data);
printf("%d\t", ob3.prev_link->data);
printf("%d", ob3.data);
return 0;
}

Long Answer Type Questions


1. Explain structure with help of an example.

Structure is a group of variables of different data types represented by a single name.


Lets take an example to understand the need of a structure in C programming.

Lets say we need to store the data of students like student name, age, address, id
etc. One way of doing this would be creating a different variable for each attribute,
however when you need to store the data of multiple students then in that case, you
would need to create these several variables again for each student. This is such a
big headache to store data in this way.

We can solve this problem easily by using structure. We can create a structure that
has members for name, id, address and age and then we can create the variables of
this structure for each student. This may sound confusing, do not worry we will
understand this with the help of example.

struct struct_name {
DataType member1_name;
DataType member2_name;
DataType member3_name;

};
Here struct_name can be anything of your choice. Members data type can be same
or different. Once we have declared the structure we can use the struct name as a
data type like int, float etc.

How to declare variable of a structure?

struct struct_name var_name;


or

struct struct_name {
DataType member1_name;
DataType member2_name;
DataType member3_name;

} var_name;
How to access data members of a structure using a struct variable?

var_name.member1_name;
var_name.member2_name;

How to assign values to structure members?

There are three ways to do this.

1) Using Dot(.) operator

var_name.memeber_name = value;
2) All members assigned in one statement

struct struct_name var_name =


{value for memeber1, value for memeber2 …so on for all the members}
3) Designated initializers – We will discuss this later at the end of this post.

#include <stdio.h>
/* Created a structure here. The name of the structure is
* StudentData.
*/
struct StudentData{
char *stu_name;
int stu_id;
int stu_age;
};
int main()
{
/* student is the variable of structure StudentData*/
struct StudentData student;

/*Assigning the values of each struct member here*/


student.stu_name = "Steve";
student.stu_id = 1234;
student.stu_age = 30;
/* Displaying the values of struct members */
printf("Student Name is: %s", student.stu_name);
printf("\nStudent Id is: %d", student.stu_id);
printf("\nStudent Age is: %d", student.stu_age);
return 0;
}
Output:

Student Name is: Steve


Student Id is: 1234
Student Age is: 30

2. Create a structure student to store the name, roll no and marks of the
students. Enter some sample values within the structure and print the
details of the student with maximum marks.

#include <stdio.h>

struct student

char name[50];

int roll;

float marks;

} s[10];

int main()

int i;
printf("Enter information of students:\n");

// storing information

for(i=0; i<10; ++i)

s[i].roll = i+1;

printf("\nFor roll number%d,\n",s[i].roll);

printf("Enter name: ");

scanf("%s",s[i].name);

printf("Enter marks: ");

scanf("%f",&s[i].marks);

printf("\n");

printf("Displaying Information:\n\n");

// displaying information

for(i=0; i<10; ++i)

printf("\nRoll number: %d\n",i+1);

printf("Name: ");
puts(s[i].name);

printf("Marks: %.1f",s[i].marks);

printf("\n");

return 0;

Output

Enter information of students:

For roll number1,


Enter name: Tom
Enter marks: 98

For roll number2,


Enter name: Jerry
Enter marks: 89
.
.
.
Displaying Information:

Roll number: 1
Name: Tom
Marks: 98
.
.
.
3. WAP to copy contents from file name ss.txt to tk.txt with the concept of file
handling.

#include <stdio.h>

#include <stdlib.h> // For exit()

int main()

FILE *fptr1, *fptr2;

char filename[100], c;

printf("Enter the filename to open for reading \n");

scanf("%s", filename);

// Open one file for reading

fptr1 = fopen(“ss.txt”, "r");

if (fptr1 == NULL)

printf("Cannot open file %s \n", filename);

exit(0);

printf("Enter the filename to open for writing \n");


scanf("%s", filename);

// Open another file for writing

fptr2 = fopen(filename, "w");

if (fptr2 == NULL)

printf("Cannot open file %s \n", filename);

exit(0);

// Read contents from file

c = fgetc(fptr1);

while (c != EOF)

fputc(c, fptr2);

c = fgetc(fptr1);

printf("\nContents copied to %s", filename);

fclose(fptr1);

fclose(fptr2);

return 0;
}

Output:

Enter the filename to open for reading

ss.txt

Enter the filename to open for writing

tk.txt

Contents copied to tk.txt

4. Write Short Notes on:

a) fopen();

File
operation Declaration & Description

Declaration: FILE *fopen (const char *filename, const char


*mode)
fopen() function is used to open a file to perform operations
such as reading, writing etc. In a C program, we declare a file
pointer and use fopen() as below. fopen() function creates a
new file if the mentioned file name does not exist.

fopen()
FILE *fp;

fp=fopen (“filename”, ”‘mode”);


Where,
fp – file pointer to the data type “FILE”.
filename – the actual file name with full path of the file.
mode – refers to the operation that will be performed on the
file. Example: r, w, a, r+, w+ and a+. Please refer below the
description for these mode of operations.

Declaration: int fclose(FILE *fp);


fclose() function closes the file that is being pointed by file
fclose()
pointer fp. In a C program, we close a file as below.
fclose (fp);

Declaration: char *gets (char *string)


gets functions is used to read the string (sequence of
gets() characters) from keyboard input. In a C program, we can read
the string from standard input/keyboard as below.
gets (string);

Declaration: int fputs (const char *string, FILE *fp)


fputs function writes string into a file pointed by fp. In a C
fputs()
program, we write string into a file as below.
fputs (fp, “some data”);

File
handling functions Description

fopen () function creates a new file or opens an


fopen () existing file.

fclose () fclose () function closes an opened file.

getw () getw () function reads an integer from file.

putw () putw () functions writes an integer to file.


fgetc () fgetc () function reads a character from file.

fputc () fputc () functions write a character to file.

gets () gets () function reads line from keyboard.

puts () puts () function writes line to o/p screen.

fgets () function reads string from a file, one line at


fgets () a time.

fputs () fputs () function writes string to a file.

feof () feof () function finds end of file.

fgetchar () function reads a character from


fgetchar () keyboard.

fprintf () fprintf () function writes formatted data to a file.

fscanf () fscanf () function reads formatted data from a file.

fputchar () function writes a character onto the


fputchar () output screen from keyboard input.

b) eof();

EOF means end of file. It's a sign that the end of a file is reached, and that there will
be no data anymore. On Linux systems and OS X, the character to input to cause an
EOF is CTRL+D. For Windows, it's CTRL+Z. Depending on the operating system, this
character will only work if it's the first character on a line, i.e. the first character after
an ENTER. Since console input is often line-oriented, the system may also not
recognize the EOF character until after you've followed it up with an ENTER And yes,
if that character is recognized as an EOF, then your program will never see the actual
character. Instead, a C program will get a -1 from getchar().

c) fread();

Description

The C library function size_t fread(void *ptr, size_t size, size_t nmemb, FILE
*stream) reads data from the given stream into the array pointed to, by ptr.

Declaration

Following is the declaration for fread() function.

size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream)

Parameters

 ptr − This is the pointer to a block of memory with a minimum size


of size*nmemb bytes.

 size − This is the size in bytes of each element to be read.

 nmemb − This is the number of elements, each one with a size of size bytes.

 stream − This is the pointer to a FILE object that specifies an input stream.

Return Value

The total number of elements successfully read are returned as a size_t object,
which is an integral data type. If this number differs from the nmemb parameter,
then either an error had occurred or the End Of File was reached.

d) fwrite();

Description
The C library function size_t fwrite(const void *ptr, size_t size, size_t nmemb,
FILE *stream) writes data from the array pointed to, by ptr to the given stream.

Declaration

Following is the declaration for fwrite() function.

size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream)

Parameters

 ptr − This is the pointer to the array of elements to be written.

 size − This is the size in bytes of each element to be written.

 nmemb − This is the number of elements, each one with a size of size bytes.

 stream − This is the pointer to a FILE object that specifies an output stream.

Return Value

This function returns the total number of elements successfully returned as a size_t
object, which is an integral data type. If this number differs from the nmemb
parameter, it will show an error.

5. Explain various file opening modes in C.


Mode of operations performed on a file in c language:
There are many modes in opening a file. Based on the mode of file, it can be opened
for reading or writing or appending the texts. They are listed below.

 r – Opens a file in read mode and sets pointer to the first character in the file. It
returns null if file does not exist.
 w – Opens a file in write mode. It returns null if file could not be opened. If file
exists, data are overwritten.
 a – Opens a file in append mode. It returns null if file couldn’t be opened.
 r+ – Opens a file for read and write mode and sets pointer to the first character
in the file.
 w+ – opens a file for read and write mode and sets pointer to the first character
in the file.
 a+ – Opens a file for read and write mode and sets pointer to the first character
in the file. But, it can’t modify existing contents.

S-ar putea să vă placă și