0% found this document useful (0 votes)
561 views18 pages

Pps Unit 05 Notes

Uploaded by

Himanshu Sahu
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)
561 views18 pages

Pps Unit 05 Notes

Uploaded by

Himanshu Sahu
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

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( [Link], "C Programming");
strcpy( [Link], "Ashok Kamthane");
strcpy( [Link], "C Programming Tutorial");
Book1.book_id = 6495;
/* Book 2 specification */
strcpy( [Link], "Programming C");
strcpy( [Link], "Balaguru Swami");

Prepared by: Shankar Sharan Tripathi Page 2


Programming for Problem Solving

strcpy( [Link], " C Programming Tutorial");


Book2.book_id = 6496;
/* print Book1 info */
printf( "Book 1 title : %s\n", [Link]);
printf( "Book 1 author : %s\n", [Link]);
printf( "Book 1 subject : %s\n", [Link]);
printf( "Book 1 book_id : %d\n\n", Book1.book_id);
/* print Book2 info */
printf( "Book 2 title : %s\n", [Link]);
printf( "Book 2 author : %s\n", [Link]);
printf( "Book 2 subject : %s\n", [Link]);
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", &[Link]);
printf("Enter roll number: ");
scanf("%d", &[Link]);
printf("Enter marks: ");
scanf("%f", &[Link]);
printf("\nDisplaying Information:\n");
printf("Name: ");
puts([Link]);
printf("Roll number: %d\n",[Link]);
printf("Marks: %.1f\n", [Link]);
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", [Link]);
printf("Name: %s\n", [Link]);
printf("Grades: %f, %f, %f\n", [Link][0], [Link][1], [Link][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};
[Link] = &node2;
printf("Node 1 data: %d\n", [Link]);
printf("Node 2 data: %d\n", [Link]->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("[Link]","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("[Link]", "r"); fp2
= fopen("[Link]", "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 "[Link]" 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 [Link] to [Link].

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("[Link]", "r");
FILE *fp2 = fopen("[Link]", "r");
FILE *fp3 = fopen("[Link]", "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 [Link] and [Link] into [Link]");
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 "[Link]"
and “[Link]” 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 [Link].

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

Common questions

Powered by AI

Pointers to structures in C hold the address of a structure variable, allowing for efficient data management and manipulation. This becomes significant when dealing with large structures or when passing structures to functions, as it avoids copying the entire structure, thus saving memory and time. Moreover, pointers to structures enable dynamic memory allocation for structures via functions like malloc. An example would be accessing a structure's members using the pointer with the '->' operator instead of the dot operator, as seen in the use of a pointer to reference a 'Student' structure and access its members like ID and grade . This method provides indirect access to structure data, enhancing flexibility in programming.

The primary difference between unions and structures in C is related to memory allocation and usage. A structure allocates space for each member, allowing simultaneous storage of all declared members, whereas a union uses the same memory location for all its members, enabling only a single member to hold a value at a time. This makes unions ideal for memory-sensitive applications where only one piece of data is needed at any point. For example, a union defined with an int, float, and char array will occupy memory equal to its largest member, depicted by its ability to store different data types in the same memory location but not simultaneously . Structures are used for data consistency, while unions are efficient in terms of memory usage.

File handling in C provides data persistence by saving data independently of the program's run time, which is crucial for data storage and management beyond program execution. Pros include storing large data sets, enabling data sharing, and facilitating data recovery. However, the complexity of file handling introduces challenges such as ensuring proper file operations (opening, reading, writing, and closing), error management during file access, and understanding various modes and their implications. For instance, incorrect file mode usage can lead to data corruption or loss . Thus, while offering significant advantages in data management, file handling demands careful implementation and error handling.

Structures in C programming allow for the grouping of different data types under a single name, which helps in organizing complex data, making it easier to manage and understand. They enable the storage of different types of data in a single entity, facilitating the creation of records like an employee or book record. For example, using a structure to manage book details can include the title, author, subject, and book_id, as shown in the program where two books are described using the structure 'Books' . This organization helps in maintaining and accessing related variables efficiently.

In C, several file opening modes determine how a file can be accessed: 'r' opens a file for reading, 'w' creates a file for writing (overwriting if the file exists), 'a' opens a file for appending new data to the end, 'r+' allows reading and writing to an existing file, 'w+' opens a file for reading and writing (and creates it if it doesn't exist), 'a+' opens for reading and writing (and creates a file if it doesn't exist, appending new data to the end if it does). Binary modes like 'rb', 'wb', and 'ab' are similar but handle binary files instead of text . These modes ensure that files are handled in a way that suits the operation being performed, whether it's reading, writing, or both.

Enumerated types (enum) in C improve code readability by allowing the programmer to define a set of named integer constants, which makes the code more understandable than using raw numbers. For example, defining an enum for days of the week with names like Mon, Tue, etc., can prevent errors associated with using arbitrary integral constants for these purposes. This also enhances maintenance, as changes to the values of these constants only need to be made in one place rather than throughout the code. Additionally, using meaningful names in place of numbers makes the code more intuitive and self-documenting .

Arrays of structures in C allow storing multiple records with multiple data types in a single array, each element of which can represent a structure. This is beneficial for handling multiple data records more easily and efficiently. For example, an array of structures can be used to store student details, with each structure representing a student's ID, name, and grade. This setup is demonstrated where three students' data are stored in an array of structures, allowing for easy traversal and display of each student's information . This approach reduces code complexity and enhances data management.

Self-referential structures are structures in C that contain a pointer to an instance of the same structure type. This concept is commonly used to create linked data structures such as linked lists, trees, and graphs. A classic application is in linked lists, where each node points to the next node in the sequence, facilitating dynamic data handling with efficient memory utilization. For example, a 'Node' structure in a linked list contains an integer data field and a pointer to the next 'Node', allowing for the creation of a dynamic sequence of nodes . This mechanism is fundamental in building complex data structures that adapt to data insertion and deletion.

File input and output in C are managed by functions like fopen(), fclose(), fprintf(), fscanf(), fgetc(), fputc(), fread(), and fwrite(). These functions handle opening files, closing files, writing data to files, reading data from files, and more complex operations like reading and writing binary data. For example, 'fopen' opens a file in the required mode, while 'fclose' ensures the file is properly closed after operations, preventing data being locked or corrupted. 'fscanf' and 'fprintf' allow for formatted reading and writing, similar to 'scanf' and 'printf', but operating on files . In practice, these functions provide the foundational operations for file manipulation, essential in many applications like data processing and persistent storage.

Pointers are crucial in creating dynamic linked data structures in C, such as linked lists, by allowing the allocation and deallocation of memory dynamically. They enable the creation of nodes where each node contains data and a pointer to the next node, allowing for flexible data storage and modification without needing contiguous memory allocation. This dynamic nature is essential for applications where data sizes are not known in advance or frequently change. For instance, creating a self-referential structure with a pointer referencing the same type of structure allows efficient management and traversal of linked nodes . However, utilizing pointers requires careful handling to avoid memory leaks and segmentation faults, necessitating robust error handling and understanding of memory allocation/deallocation.

You might also like