SlideShare a Scribd company logo
14
Most read
16
Most read
22
Most read
Programming for Problem
Solving
Topics: Unit 5
Unit 5
• STRUCTURES AND UNIONS
• Defining a structure, processing a structure,
• Structures and pointers,
• Passing structures to a function,
• Self-referential structures,
• Unions
• User-defined data types: typedef, enum.
• Files
• Opening a file, Reading from a file,
• Writing to a file and Appending to a file
• Closing a File,
• Error handling functions in files,
Passing Structure to a function
• Passing structure to a function by value
• Passing structure to a function by
address(reference)
Passing structure to a function by value
struct student { int id; char name[20]; float percentage; };
void func(struct student record);
main()
{
struct student record;
record.id=1;
strcpy(record.name, “Ritchie");
record.percentage = 86.5;
func(record);
}
void func(struct student record)
{
printf(" Id is: %d n", record.id); printf(" Name is: %s n", record.name);
printf(" Percentage is: %f n", record.percentage);
}
Passing structure to function in C by address
struct student { int id; char name[20]; float
percentage; };
void func(struct student *record);
int main()
{
struct student record; record.id=1;
strcpy(record.name, “Bjarne");
record.percentage = 86.5;
func(&record);
}
void func(struct student *record)
{
printf(" Id is: %d ", record->id); printf(" Name is: %s“,record->name);
printf(" Percentage is: %f n", record->percentage);
}
SELF-REFERENTIAL STRUCTURE
• A structure definition which includes at least
one member as a pointer to the same
structure is known as self-referential structure.
• Can be linked together to form useful data
structures such as lists, queues, stacks and
trees.
• Terminated with a NULL pointer (0).
Self referential structure
Syntax:
struct structure_name
{
datatype datatype_name;
structure_name * pointer_name;
}
Example:
struct node
{
int data;
struct node *next;
};
Example: Self referential structure
struct node
{
int value;
struct node *next;
};
int main() {
struct node *head;
struct node *one = NULL;
struct node *two = NULL;
struct node *three = NULL;
one=malloc(sizeof(struct node));
two=malloc(sizeof(struct node));
three=malloc(sizeof(struct node));
one->value = 1; two->value = 2;
three->value = 3;
one->next = two; two->next=three;
three->next = NULL;
head = one;
printLinkedlist(head);
}
PPS Notes Unit 5.pdf
typedef
int main()
{
typedef int Number;
Number num1 = 40,num2 = 20;
Number answer;
answer = num1 + num2;
printf("Answer : %d",answer);
return(0);
}
Typedef is a keyword that is used to give a new symbolic
name for the existing name in a C program.
typedef is a keyword used in C language to assign
alternative names to existing types.
enum
enum week
{
sunday, monday, tuesday, wednesday, thursday,
friday, Saturday };
int main()
{
enum week today;
today=wednesday;
printf("%d day",today+1);
return 0;
}
An enumeration is a user-defined data type consists of integral constants
and each integral constant is give a name.
enum type_name { value1, value2,...,valueN };
File in C Language
• A file represents a sequence of bytes on the
disk where a group of related data is stored.
• In C language, we use a structure pointer of
file type to declare a file.
• FILE *fp;
13
Basic operations on a file
• Open
• Read
• Write
• Close
• Mainly we want to do read or write, but a file has to
be opened before read/write, and should be closed
after all read/write is over
14
Opening a File: fopen()
• FILE * is a datatype used to represent a pointer to a
file
• fopen takes two parameters, the name of the file
to open and the mode in which it is to be opened
• It returns the pointer to the file if the file is opened
successfully, or NULL to indicate that it is unable to
open the file
15
Modes for opening files
• The second argument of fopen is the mode in
which we open the file.
– "r" : opens a file for reading (can only read)
• Error if the file does not already exists
• "r+" : allows write also
– "w" : creates a file for writing (can only write)
• Will create the file if it does not exist
• Caution: writes over all previous contents if the flle
already exists
• "w+" : allows read also
– "a" : opens a file for appending (write at the
end of the file)
• "a+" : allows read also
16
Example: opening file.dat for write
FILE *fptr;
char filename[ ]= "file2.dat";
fptr = fopen (filename,"w");
if (fptr == NULL)
{
printf (“ERROR IN FILE CREATION”);
}
Input/Output operations on files
• C provides several different
functions for reading/writing
• getc() – read a character
• putc() – write a character
• fprintf() – write set of data values
• fscanf() – read set of data values
• getw() – read integer
• putw() – write integer
getc() and putc()
• handle one character at a time like getchar() and
putchar()
• syntax: putc(c,fp1);
– c : a character variable
– fp1 : pointer to file opened with mode w
• syntax: c = getc(fp2);
– c : a character variable
– fp2 : pointer to file opened with mode r
• file pointer moves by one character position after
every getc() and putc()
• getc() returns end-of-file marker EOF when file end
reached
FILE *fptr ;
int i, n, rollno, s1, s2; char name[30];
fptr = fopen("STUDENT.DAT", "w");
// accept n
for(i = 0 ; i < n ; i++)
{
//accept name,rollno,s1, s2 marks
fprintf(fptr,"%d %s %d %d n",rollno,name, s1, s2);
}
fclose(fptr);
fptr = fopen("STUDENT.DAT", "r");
printf("nRoll No. Name tt Sub1 t Sub2 t Totalnn");
for(i = 0; i < n; i++)
{
fscanf(fptr,"%d %s %d %d n", &rollno, name, &s1, &s2);
printf("%d t %s tt %d t %d t %d n",rollno,name,
s1, s2, s1 + s2);
}
fclose(fptr); }
Program to read/write using getc/putc
#include <stdio.h>
main()
{ FILE *fp1;
char c;
f1= fopen(“INPUT”, “w”);
while((c=getchar()) != EOF)
putc(c,f1);
fclose(f1);
f1=fopen(“INPUT”, “r”);
while((c=getc(f1))!=EOF)
printf(“%c”, c);
fclose(f1);
} /*end main */
C program using getw, putw,fscanf, fprintf
#include <stdio.h>
main()
{ int i,sum1=0;
FILE *f1;
/* open files */
f1 = fopen("int_data.bin","w");
/* write integers to files in binary
and text format*/
for(i=10;i<15;i++) putw(i,f1);
fclose(f1);
f1 = fopen("int_data.bin","r");
while((i=getw(f1))!=EOF)
{ sum1+=i;
printf("binary file: i=%dn",i);
} /* end while getw */
printf("binary sum=%d,sum1);
fclose(f1);
}
#include <stdio.h>
main()
{ int i, sum2=0;
FILE *f2;
/* open files */
f2 = fopen("int_data.txt","w");
/* write integers to files in binary and
text format*/
for(i=10;i<15;i++) printf(f2,"%dn",i);
fclose(f2);
f2 = fopen("int_data.txt","r");
while(fscanf(f2,"%d",&i)!=EOF)
{ sum2+=i; printf("text file:
i=%dn",i);
} /*end while fscanf*/
printf("text sum=%dn",sum2);
fclose(f2);
}
Errors that occur during I/O
• Typical errors that occur
– trying to read beyond end-of-file
– trying to use a file that has not been opened
– perform operation on file not permitted by ‘fopen’ mode
– open file with invalid filename
– write to write-protected file
Error handling
• given file-pointer, check if EOF reached, errors
while handling file, problems opening file etc.
• check if EOF reached: feof()
• feof() takes file-pointer as input, returns nonzero
if all data read and zero otherwise
if(feof(fp))
printf(“End of datan”);
• ferror() takes file-pointer as input, returns
nonzero integer if error detected else returns
zero
if(ferror(fp) !=0)
printf(“An error has occurredn”);
Error while opening file
• if file cannot be opened then fopen returns a
NULL pointer
• Good practice to check if pointer is NULL before
proceeding
fp = fopen(“input.dat”, “r”);
if (fp == NULL)
printf(“File could not be opened n ”);

More Related Content

PDF
Modular Programming in C
PDF
PPS Arrays Matrix operations
PDF
Programming for Problem Solving
PPT
Pointer in C
PDF
C Programming Storage classes, Recursion
PPTX
Function in C program
PPTX
C Programming: Structure and Union
PDF
Python programming : Arrays
Modular Programming in C
PPS Arrays Matrix operations
Programming for Problem Solving
Pointer in C
C Programming Storage classes, Recursion
Function in C program
C Programming: Structure and Union
Python programming : Arrays

What's hot (20)

PPTX
Pointer in c
PPT
File handling in c
PPTX
C Programming : Pointers and Strings
PDF
C++ tokens and expressions
PPTX
Queue Implementation Using Array & Linked List
PDF
C Pointers
PPSX
Function in c
PPTX
C programming - String
PDF
C Recursion, Pointers, Dynamic memory management
PPT
Multidimensional array in C
PPTX
Object Oriented Programming
PPTX
Linear differential equation
PPT
Structure of a C program
PPTX
Pointers,virtual functions and polymorphism cpp
PPTX
Python Datatypes by SujithKumar
PPTX
File handling in c
PPTX
The string class
PPTX
Array Of Pointers
PPT
Inheritance OOP Concept in C++.
PPTX
Pointers and Dynamic Memory Allocation
Pointer in c
File handling in c
C Programming : Pointers and Strings
C++ tokens and expressions
Queue Implementation Using Array & Linked List
C Pointers
Function in c
C programming - String
C Recursion, Pointers, Dynamic memory management
Multidimensional array in C
Object Oriented Programming
Linear differential equation
Structure of a C program
Pointers,virtual functions and polymorphism cpp
Python Datatypes by SujithKumar
File handling in c
The string class
Array Of Pointers
Inheritance OOP Concept in C++.
Pointers and Dynamic Memory Allocation
Ad

Similar to PPS Notes Unit 5.pdf (20)

PPT
Unit5
PPTX
Programming in C
PPTX
Programming in C
DOCX
C UNIT-5 PREPARED BY M V BRAHMANANDA REDDY
PPT
file handling1
PPTX
Data Structure Using C - FILES
PPTX
5 Structure & File.pptx
PPTX
want to learn files,then just use this ppt to learn
PPT
C-Programming Chapter 5 File-handling-C.ppt
PPSX
1file handling
PPT
C-Programming Chapter 5 File-handling-C.ppt
PPSX
File mangement
PPT
file handling, dynamic memory allocation
PPT
Files_in_C.ppt
PPTX
File management
PPT
Unit5 (2)
PDF
Advance C Programming UNIT 4-FILE HANDLING IN C.pdf
PPTX
programming in C and Datastructures deepdive
PPT
Unit5 C
Unit5
Programming in C
Programming in C
C UNIT-5 PREPARED BY M V BRAHMANANDA REDDY
file handling1
Data Structure Using C - FILES
5 Structure & File.pptx
want to learn files,then just use this ppt to learn
C-Programming Chapter 5 File-handling-C.ppt
1file handling
C-Programming Chapter 5 File-handling-C.ppt
File mangement
file handling, dynamic memory allocation
Files_in_C.ppt
File management
Unit5 (2)
Advance C Programming UNIT 4-FILE HANDLING IN C.pdf
programming in C and Datastructures deepdive
Unit5 C
Ad

More from Sreedhar Chowdam (20)

PDF
DBMS Nested & Sub Queries Set operations
PDF
DBMS Notes selection projection aggregate
PDF
Database management systems Lecture Notes
PPT
Advanced Data Structures & Algorithm Analysi
PDF
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
PPTX
Design and Analysis of Algorithms Lecture Notes
PDF
Design and Analysis of Algorithms (Knapsack Problem)
PDF
DCCN Network Layer congestion control TCP
PDF
Data Communication and Computer Networks
PDF
DCCN Unit 1.pdf
PDF
Data Communication & Computer Networks
PDF
Big Data Analytics Part2
PDF
Python Programming: Lists, Modules, Exceptions
PDF
Python Programming by Dr. C. Sreedhar.pdf
PDF
Python Programming Strings
PDF
Python Programming
PDF
Python Programming
PDF
Programming For Problem Solving Lecture Notes
PDF
Big Data Analytics
PDF
Data Structures Notes 2021
DBMS Nested & Sub Queries Set operations
DBMS Notes selection projection aggregate
Database management systems Lecture Notes
Advanced Data Structures & Algorithm Analysi
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms Lecture Notes
Design and Analysis of Algorithms (Knapsack Problem)
DCCN Network Layer congestion control TCP
Data Communication and Computer Networks
DCCN Unit 1.pdf
Data Communication & Computer Networks
Big Data Analytics Part2
Python Programming: Lists, Modules, Exceptions
Python Programming by Dr. C. Sreedhar.pdf
Python Programming Strings
Python Programming
Python Programming
Programming For Problem Solving Lecture Notes
Big Data Analytics
Data Structures Notes 2021

Recently uploaded (20)

PDF
PRIZ Academy - 9 Windows Thinking Where to Invest Today to Win Tomorrow.pdf
PPTX
Sustainable Sites - Green Building Construction
PDF
Embodied AI: Ushering in the Next Era of Intelligent Systems
PDF
Mohammad Mahdi Farshadian CV - Prospective PhD Student 2026
PPTX
Strings in CPP - Strings in C++ are sequences of characters used to store and...
PPTX
MCN 401 KTU-2019-PPE KITS-MODULE 2.pptx
PDF
July 2025 - Top 10 Read Articles in International Journal of Software Enginee...
PPTX
Infosys Presentation by1.Riyan Bagwan 2.Samadhan Naiknavare 3.Gaurav Shinde 4...
DOCX
ASol_English-Language-Literature-Set-1-27-02-2023-converted.docx
PDF
Structs to JSON How Go Powers REST APIs.pdf
PPT
Project quality management in manufacturing
PPTX
Construction Project Organization Group 2.pptx
PPTX
Welding lecture in detail for understanding
PPTX
Lecture Notes Electrical Wiring System Components
PPT
Mechanical Engineering MATERIALS Selection
PPTX
UNIT 4 Total Quality Management .pptx
PDF
Operating System & Kernel Study Guide-1 - converted.pdf
PPTX
Recipes for Real Time Voice AI WebRTC, SLMs and Open Source Software.pptx
PPTX
KTU 2019 -S7-MCN 401 MODULE 2-VINAY.pptx
PPTX
web development for engineering and engineering
PRIZ Academy - 9 Windows Thinking Where to Invest Today to Win Tomorrow.pdf
Sustainable Sites - Green Building Construction
Embodied AI: Ushering in the Next Era of Intelligent Systems
Mohammad Mahdi Farshadian CV - Prospective PhD Student 2026
Strings in CPP - Strings in C++ are sequences of characters used to store and...
MCN 401 KTU-2019-PPE KITS-MODULE 2.pptx
July 2025 - Top 10 Read Articles in International Journal of Software Enginee...
Infosys Presentation by1.Riyan Bagwan 2.Samadhan Naiknavare 3.Gaurav Shinde 4...
ASol_English-Language-Literature-Set-1-27-02-2023-converted.docx
Structs to JSON How Go Powers REST APIs.pdf
Project quality management in manufacturing
Construction Project Organization Group 2.pptx
Welding lecture in detail for understanding
Lecture Notes Electrical Wiring System Components
Mechanical Engineering MATERIALS Selection
UNIT 4 Total Quality Management .pptx
Operating System & Kernel Study Guide-1 - converted.pdf
Recipes for Real Time Voice AI WebRTC, SLMs and Open Source Software.pptx
KTU 2019 -S7-MCN 401 MODULE 2-VINAY.pptx
web development for engineering and engineering

PPS Notes Unit 5.pdf

  • 2. Unit 5 • STRUCTURES AND UNIONS • Defining a structure, processing a structure, • Structures and pointers, • Passing structures to a function, • Self-referential structures, • Unions • User-defined data types: typedef, enum. • Files • Opening a file, Reading from a file, • Writing to a file and Appending to a file • Closing a File, • Error handling functions in files,
  • 3. Passing Structure to a function • Passing structure to a function by value • Passing structure to a function by address(reference)
  • 4. Passing structure to a function by value struct student { int id; char name[20]; float percentage; }; void func(struct student record); main() { struct student record; record.id=1; strcpy(record.name, “Ritchie"); record.percentage = 86.5; func(record); } void func(struct student record) { printf(" Id is: %d n", record.id); printf(" Name is: %s n", record.name); printf(" Percentage is: %f n", record.percentage); }
  • 5. Passing structure to function in C by address struct student { int id; char name[20]; float percentage; }; void func(struct student *record); int main() { struct student record; record.id=1; strcpy(record.name, “Bjarne"); record.percentage = 86.5; func(&record); } void func(struct student *record) { printf(" Id is: %d ", record->id); printf(" Name is: %s“,record->name); printf(" Percentage is: %f n", record->percentage); }
  • 6. SELF-REFERENTIAL STRUCTURE • A structure definition which includes at least one member as a pointer to the same structure is known as self-referential structure. • Can be linked together to form useful data structures such as lists, queues, stacks and trees. • Terminated with a NULL pointer (0).
  • 7. Self referential structure Syntax: struct structure_name { datatype datatype_name; structure_name * pointer_name; } Example: struct node { int data; struct node *next; };
  • 8. Example: Self referential structure struct node { int value; struct node *next; }; int main() { struct node *head; struct node *one = NULL; struct node *two = NULL; struct node *three = NULL; one=malloc(sizeof(struct node)); two=malloc(sizeof(struct node)); three=malloc(sizeof(struct node)); one->value = 1; two->value = 2; three->value = 3; one->next = two; two->next=three; three->next = NULL; head = one; printLinkedlist(head); }
  • 10. typedef int main() { typedef int Number; Number num1 = 40,num2 = 20; Number answer; answer = num1 + num2; printf("Answer : %d",answer); return(0); } Typedef is a keyword that is used to give a new symbolic name for the existing name in a C program. typedef is a keyword used in C language to assign alternative names to existing types.
  • 11. enum enum week { sunday, monday, tuesday, wednesday, thursday, friday, Saturday }; int main() { enum week today; today=wednesday; printf("%d day",today+1); return 0; } An enumeration is a user-defined data type consists of integral constants and each integral constant is give a name. enum type_name { value1, value2,...,valueN };
  • 12. File in C Language • A file represents a sequence of bytes on the disk where a group of related data is stored. • In C language, we use a structure pointer of file type to declare a file. • FILE *fp;
  • 13. 13 Basic operations on a file • Open • Read • Write • Close • Mainly we want to do read or write, but a file has to be opened before read/write, and should be closed after all read/write is over
  • 14. 14 Opening a File: fopen() • FILE * is a datatype used to represent a pointer to a file • fopen takes two parameters, the name of the file to open and the mode in which it is to be opened • It returns the pointer to the file if the file is opened successfully, or NULL to indicate that it is unable to open the file
  • 15. 15 Modes for opening files • The second argument of fopen is the mode in which we open the file. – "r" : opens a file for reading (can only read) • Error if the file does not already exists • "r+" : allows write also – "w" : creates a file for writing (can only write) • Will create the file if it does not exist • Caution: writes over all previous contents if the flle already exists • "w+" : allows read also – "a" : opens a file for appending (write at the end of the file) • "a+" : allows read also
  • 16. 16 Example: opening file.dat for write FILE *fptr; char filename[ ]= "file2.dat"; fptr = fopen (filename,"w"); if (fptr == NULL) { printf (“ERROR IN FILE CREATION”); }
  • 17. Input/Output operations on files • C provides several different functions for reading/writing • getc() – read a character • putc() – write a character • fprintf() – write set of data values • fscanf() – read set of data values • getw() – read integer • putw() – write integer
  • 18. getc() and putc() • handle one character at a time like getchar() and putchar() • syntax: putc(c,fp1); – c : a character variable – fp1 : pointer to file opened with mode w • syntax: c = getc(fp2); – c : a character variable – fp2 : pointer to file opened with mode r • file pointer moves by one character position after every getc() and putc() • getc() returns end-of-file marker EOF when file end reached
  • 19. FILE *fptr ; int i, n, rollno, s1, s2; char name[30]; fptr = fopen("STUDENT.DAT", "w"); // accept n for(i = 0 ; i < n ; i++) { //accept name,rollno,s1, s2 marks fprintf(fptr,"%d %s %d %d n",rollno,name, s1, s2); } fclose(fptr); fptr = fopen("STUDENT.DAT", "r"); printf("nRoll No. Name tt Sub1 t Sub2 t Totalnn"); for(i = 0; i < n; i++) { fscanf(fptr,"%d %s %d %d n", &rollno, name, &s1, &s2); printf("%d t %s tt %d t %d t %d n",rollno,name, s1, s2, s1 + s2); } fclose(fptr); }
  • 20. Program to read/write using getc/putc #include <stdio.h> main() { FILE *fp1; char c; f1= fopen(“INPUT”, “w”); while((c=getchar()) != EOF) putc(c,f1); fclose(f1); f1=fopen(“INPUT”, “r”); while((c=getc(f1))!=EOF) printf(“%c”, c); fclose(f1); } /*end main */
  • 21. C program using getw, putw,fscanf, fprintf #include <stdio.h> main() { int i,sum1=0; FILE *f1; /* open files */ f1 = fopen("int_data.bin","w"); /* write integers to files in binary and text format*/ for(i=10;i<15;i++) putw(i,f1); fclose(f1); f1 = fopen("int_data.bin","r"); while((i=getw(f1))!=EOF) { sum1+=i; printf("binary file: i=%dn",i); } /* end while getw */ printf("binary sum=%d,sum1); fclose(f1); } #include <stdio.h> main() { int i, sum2=0; FILE *f2; /* open files */ f2 = fopen("int_data.txt","w"); /* write integers to files in binary and text format*/ for(i=10;i<15;i++) printf(f2,"%dn",i); fclose(f2); f2 = fopen("int_data.txt","r"); while(fscanf(f2,"%d",&i)!=EOF) { sum2+=i; printf("text file: i=%dn",i); } /*end while fscanf*/ printf("text sum=%dn",sum2); fclose(f2); }
  • 22. Errors that occur during I/O • Typical errors that occur – trying to read beyond end-of-file – trying to use a file that has not been opened – perform operation on file not permitted by ‘fopen’ mode – open file with invalid filename – write to write-protected file
  • 23. Error handling • given file-pointer, check if EOF reached, errors while handling file, problems opening file etc. • check if EOF reached: feof() • feof() takes file-pointer as input, returns nonzero if all data read and zero otherwise if(feof(fp)) printf(“End of datan”); • ferror() takes file-pointer as input, returns nonzero integer if error detected else returns zero if(ferror(fp) !=0) printf(“An error has occurredn”);
  • 24. Error while opening file • if file cannot be opened then fopen returns a NULL pointer • Good practice to check if pointer is NULL before proceeding fp = fopen(“input.dat”, “r”); if (fp == NULL) printf(“File could not be opened n ”);