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

Pps Unit 05 Notes

Uploaded by

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

Pps Unit 05 Notes

Uploaded by

Himanshu Sahu
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

Programming for Problem Solving

Syllabus of UNIT V: Structures and File handling

Structure: Definition, Initialization and Accessing of Structures, Arrays of Structures,


Array within Structures, Pointers to Structures, Self-Referential Structures, notion of
linked list. File handling: Concept of Files, File opening in various modes and closing of
a file, Reading from a text file, writing onto a text file, copy content from one file to
another file.

Q.1 Write short notes on


1. structure 2. union 3. enum
Answer:

1. Structure
Structure in c is a user-defined data type that enables us to store the collection of
different data types. Each element of a structure is called a member. The
struct keyword is used to define the structure.
The syntax to define the structure:
struct structure_name
{
data_type member1;
data_type member2;
.
data_type memeberN;
};

Example to define a structure for an entity employee in c.


struct employee
{
int id;
char name[20];
float salary;
};

The following image shows the memory allocation of the structure employee
that is defined in the above example.

Prepared by: Shankar Sharan Tripathi Page 1


Programming for Problem Solving

1. Write a C program to create Book Details using structure.


#include <stdio.h>
#include <string.h>
struct Books
{
char title[50];
char author[50];
char subject[100];
int book_id;
};
int main( )
{
struct Books Book1; /* Declare variable (i.e. Book1) of structure i.e. Book */
struct Books Book2; /* Declare variable (i.e. Book2) of structure i.e. Book */

/* Book 1 specification */
strcpy( Book1.title, "C Programming");
strcpy( Book1.author, "Ashok Kamthane");
strcpy( Book1.subject, "C Programming Tutorial");
Book1.book_id = 6495;
/* Book 2 specification */
strcpy( Book2.title, "Programming C");
strcpy( Book2.author, "Balaguru Swami");

Prepared by: Shankar Sharan Tripathi Page 2


Programming for Problem Solving

strcpy( Book2.subject, " C Programming Tutorial");


Book2.book_id = 6496;
/* print Book1 info */
printf( "Book 1 title : %s\n", Book1.title);
printf( "Book 1 author : %s\n", Book1.author);
printf( "Book 1 subject : %s\n", Book1.subject);
printf( "Book 1 book_id : %d\n\n", Book1.book_id);
/* print Book2 info */
printf( "Book 2 title : %s\n", Book2.title);
printf( "Book 2 author : %s\n", Book2.author);
printf( "Book 2 subject : %s\n", Book2.subject);
printf( "Book 2 book_id : %d\n", Book2.book_id);
return 0;
}

Output:
Book 1 title : C Programming
Book 1 author : Ashok Kamthane
Book 1 subject : C Programming Tutorial
Book 1 book_id : 6495

Book 2 title : Programming C


Book 2 author : Balaguru Swami
Book 2 subject : C Programming Tutorial
Book 2 book_id : 6496

Prepared by: Shankar Sharan Tripathi Page 3


Programming for Problem Solving

2. Write a C program to create Student Details using structure. And store the
Information of one student and Display it.

#include <stdio.h>
struct student
{
char name[50];
int roll;
float marks;
} s;

int main()
{
printf("Enter information:\n");
printf("Enter name: ");
scanf("%s", &s.name);
printf("Enter roll number: ");
scanf("%d", &s.roll);
printf("Enter marks: ");
scanf("%f", &s.marks);
printf("\nDisplaying Information:\n");
printf("Name: ");
puts(s.name);
printf("Roll number: %d\n",s.roll);
printf("Marks: %.1f\n", s.marks);
return 0;
}

Output:
Enter information:
Enter name: Amit
Enter roll number: 2
Enter marks: 56

Displaying Information:
Name: Amit
Roll number: 2
Marks: 56

Prepared by: Shankar Sharan Tripathi Page 4


Programming for Problem Solving

2. union
A union is a special data type available in C that allows storing different data types in
the same memory location. You can define a union with many members, but only one
member can contain a value at any given time. Unions provide an efficient way of
using the same memory location for multiple-purpose.
The syntax to define union in c.
union union_name
{
data_type member1;
data_type member2;
.
.
data_type memeberN;
};

Example:

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

The memory occupied by a union will be large enough to hold the largest member of
the union. Data type will occupy 20 bytes of memory space because this is the
maximum space which can be occupied by a character string.

#include <stdio.h>
#include <string.h>
union Data
{
int i;
float f;
char str[20];
};

Prepared by: Shankar Sharan Tripathi Page 5


Programming for Problem Solving

int main( )
{
union Data data;
printf( "Memory size occupied by data : %d
%d\n", sizeof(data));
return 0;
}

Output:
Memory size occupied by data: 20

Difference

Prepared by: Shankar Sharan Tripathi Page 6


Programming for Problem Solving

3. Enumeration (or enum) in C

Enumeration is a user defined datatype in C language. It is used to assign names to the


integral constant which makes a program easy to read and maintain. The keyword
“enum” is used to declare an enumeration.
syntax of enum in C language,
enum enum_name{const1, const2, ....... };
Example
#include<stdio.h>
enum week{Mon=10, Tue, Wed, Thur, Fri, Sat, Sun};
int main()
{
printf("The value of week: %d\t%d\t%d\t%d\t%d\t%d\t%d\n",Mon , Tue, Wed,
Thur, Fri, Sat, Sun);
return 0;
}

Output
The value of week: 10 11 12 13 14 15 16

Prepared by: Shankar Sharan Tripathi Page 7


Programming for Problem Solving

Arrays of Structures
An array of structures is an array where each element is a structure. This allows you to
store multiple records of different data types in a single array.
Example:
#include <stdio.h>
struct Student
{
int id;
char name[50];
float grade;
};
int main()
{
struct Student students[3] = {{1, "Alice", 85.5}, {2, "Bob", 92.0},{3, "Charlie", 78.4}
};
for (int i = 0; i < 3; i++)
{
printf("Student ID: %d\n", students[i].id);
printf("Name: %s\n", students[i].name);
printf("Grade: %.2f\n\n", students[i].grade);
}
return 0;
}

Prepared by: Shankar Sharan Tripathi Page 8


Programming for Problem Solving

Array within Structures


An array can be a member of a structure. This allows you to store multiple values of
the same type within a structure.
Example:
#include <stdio.h>
struct Student
{
int id;
char name[50];
float grd[3]; // Array of grades for each student
};
int main()
{
struct Student student1 = {1, "Alice", {85.5, 90.2, 88.0}};
printf("Student ID: %d\n", student1.id);
printf("Name: %s\n", student1.name);
printf("Grades: %f, %f, %f\n", student1.grd[0], student1.grd[1], student1.grd[2]);
return 0;
}

Prepared by: Shankar Sharan Tripathi Page 9


Programming for Problem Solving

Pointers to Structures
Pointers to structures allow you to access structure members using pointers. This is
particularly useful for dynamic memory allocation or when passing structures to
functions.
Example:
#include <stdio.h>
struct Student
{
int id;
char name[50];
float grade;
};

int main()
{
struct Student student1 = {1, "Alice", 88.5};
struct Student *ptr = &student1;
printf("Student ID: %d\n", ptr->id);
printf("Name: %s\n", ptr->name);
printf("Grade: %.2f\n", ptr->grade);
return 0;
}

Prepared by: Shankar Sharan Tripathi Page 10


Programming for Problem Solving

Self-Referential Structures
A self-referential structure is a structure that contains a pointer to an instance of the
same structure. This is commonly used in the creation of linked lists.
Example:
#include <stdio.h>
struct Node
{
int data;
struct Node *next;
};
int main()
{
struct Node node1 = {10, NULL};
struct Node node2 = {20, NULL};
node1.next = &node2;
printf("Node 1 data: %d\n", node1.data);
printf("Node 2 data: %d\n", node1.next->data);
return 0;
}

Prepared by: Shankar Sharan Tripathi Page 11


Q.1 Explain various file Opening modes /opening a File/Creating a File & closing
a File.

Answer:
Opening a file:
The fopen() function is used to create a new file or to open an existing file.

Syntax:
*fp = FILE *fopen(const char *filename, const char *mode);
Here, *fp is the FILE pointer (FILE *fp), which will hold the reference to the opened (or
created) file.

Filename is the name of the file to be opened and mode specifies the purpose of opening
the file. Mode can be of following types,
mode description
r Opens a text file in reading mode.
w Opens or create a text file in writing mode.
a Opens a text file in append mode.
r+ Opens a text file in both reading and writing mode.
w+ Opens a text file in both reading and writing mode.
a+ Opens a text file in both reading and writing mode.
rb Opens a binary file in reading mode.
wb Opens or create a binary file in writing mode.
ab Opens a binary file in append mode.
rb+ Opens a binary file in both reading and writing mode.
wb+ Opens a binary file in both reading and writing mode.
ab+ Opens a binary file in both reading and writing mode.

Prepared By: - S. S. Tripathi Page 1


Closing a File
The fclose() function is used to close an already opened file.
Syntax :
int fclose( FILE *fp);
Here fclose() function closes the file and returns zero on success, or EOF if there is an
error in closing the file. This EOF is a constant defined in the header file stdio.h.
Input/Output operation on File
In the above table we have discussed about various file I/O functions to perform reading
and writing on file. getc() and putc() are the simplest functions which can be used to read
and write individual characters to a file.
#include <stdio.h>
#include <stdlib.h>
int main()
{ int num;
FILE *fptr;
fptr = fopen("program.txt","w");
if(fptr == NULL)
{ printf("Error!");
exit(1);
}
printf("Enter num: ");
scanf("%d",&num);
fprintf(fptr,"%d",num);
fclose(fptr);
return 0;
}

HOW TO RUN (TURBO C++):


STEP 1: Compile the C Program and RUN it.
STEP 2: Enter num: 1232
STEP 3: Now a new file will be created with a name "program.c" and all the content of the
file is 1232

Prepared By: - S. S. Tripathi Page 2


Q.2 Write a C Program to Copy the Contents from One File to Another file.
Answer:
#include <stdio.h>
int main()
{
FILE *fp1, *fp2;
char ch;
fp1 = fopen("abc.txt", "r"); fp2
= fopen("xyz.txt", "w");
while((ch = getc(fp1)) != EOF)
putc(ch, fp2);
fclose(fp1);
fclose(fp2);
return 0;
}

HOW TO RUN (TURBO C++):


STEP 1: Create a New Text Document, write content on it and Rename it as "abc.txt" and
save in the BIN folder.

STEP 2: Now Compile the C Program and RUN it.

STEP 3: Now a new file will be created with a name "xyz.c" and all the content would
copy from abc.txt to xyz.txt.

Prepared By: - S. S. Tripathi Page 3


Q.3 Write a C Program to concatenate two files in third file.

Answer:

#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fp1 = fopen("file1.txt", "r");
FILE *fp2 = fopen("file2.txt", "r");
FILE *fp3 = fopen("file3.txt", "w");
char c;
if (fp1 == NULL || fp2 == NULL || fp3 == NULL)
{
puts("Could not open files");
exit(0);
}
while ((c = fgetc(fp1)) != EOF)
fputc(c, fp3);
while ((c = fgetc(fp2)) != EOF)
fputc(c, fp3);
printf("Merged file1.txt and file2.txt into file3.txt");
fclose(fp1);
fclose(fp2);
fclose(fp3);
return 0;
}

HOW TO RUN (TURBO C++):


STEP 1: Create Two New Text Document, write content on it and Rename it as "file1.txt"
and “file2.txt” and save in the BIN folder.

STEP 2: Now Compile the C Program and RUN it.

STEP 3: Now a new file will be created with a name “file3.c" and all the content of file1
and file2 would concatenate in file3.txt.

Prepared By: - S. S. Tripathi Page 4


Q.4 write functions used in file handling.
or
Explain input and output functions in file handling with suitable program.

Answer:

File Handling in C
File handling in C enables us to create, update, read, and delete the files stored on the
local file system through our C program. The following operations can be performed on a
file.
1. Creation of the new file
2. Opening an existing file
3. Reading from the file
4. Writing to the file
5. Deleting the file

Functions for file handling


There are many functions in the C library to open, read, write, search and close the file.
Lists of file functions are given below:

No. Function Description


1 fopen() opens new or existing file
2 fprintf() write data into the file
3 fscanf() reads data from the file
4 fputc() writes a character into the file
5 fgetc() reads a character from file
6 fclose() closes the file
7 fseek() sets the file pointer to given position
8 fputw() writes an integer to file
9 fgetw() reads an integer from file
10 ftell() returns current position
11 rewind() sets the file pointer to the beginning of the file
12 feof() feof functions is used to find the end of a file.
13 fread() The fread() function is used to read bytes form the file.

Prepared By: - S. S. Tripathi Page 5


Problem Solving & Logic Building Using C
14 fwrite() used to write records to the file. record may be an array / structure.
15 ferror() tests the error indicator for the given stream.
16 gets () gets () function reads line from keyboard.
17 puts () puts () function writes line to o/p screen.
18 fgets () fgets () function reads string from a file, one line at a time.
19 fputs () fputs () function writes string to a file.
20 fgetchar () fgetchar () function reads a character from keyboard.
21 fputchar () writes a character onto the output screen from keyboard input.
22 SEEK_SET SEEK_SET moves file pointer position to the beginning of the file.
23 SEEK_CUR SEEK_CUR moves file pointer position to given location.
24 SEEK_END SEEK_END moves file pointer position to the end of file.
25 getc () getc () function reads character from file.
26 getch () getch () function reads character from keyboard.
27 getche () reads character from keyboard & echoes to o/p screen.
28 getchar () getchar () function reads character from keyboard.
29 putc () putc () function writes a character to file.
30 putchar () putchar () function writes a character to screen.
31 printf () printf () function writes formatted data to screen.
32 sprintf () sprinf () function writes formatted output to string.
33 scanf () scanf () function reads formatted data from keyboard.
34 sscanf () sscanf () function Reads formatted input from a string.
35 remove () remove () function deletes a file.
36 fflush () fflush () function flushes a file.

Prepared By: - S. S. Tripathi Page 6


Problem Solving & Logic Building Using C

Example Program For Fopen(), Fclose(), Gets() And Fputs() Functions

# include <stdio.h>
# include <string.h>
int main( )
{
FILE *fp ;
char data[50];
printf( "Opening the file test.c in write mode" ) ;
fp = fopen("test.c", "w") ;
if ( fp == NULL )
{
printf( "Could not open file test.c" ) ;
return 1;
}
printf( "\n Enter some text from keyboard to write in the file test.c" ) ;
while ( strlen ( gets( data ) ) > 0 )
{
fputs(data, fp) ;
fputs("\n", fp) ;
}
printf("Closing the file test.c") ;
fclose(fp) ;
return 0;
}

Prepared By: - S. S. Tripathi Page 7

You might also like