SlideShare una empresa de Scribd logo
1 de 24
Descargar para leer sin conexión
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);
}
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 ”);

Más contenido relacionado

La actualidad más candente (20)

C Token’s
C Token’sC Token’s
C Token’s
 
Data type in c
Data type in cData type in c
Data type in c
 
String c
String cString c
String c
 
C programming - String
C programming - StringC programming - String
C programming - String
 
MANAGING INPUT AND OUTPUT OPERATIONS IN C MRS.SOWMYA JYOTHI.pdf
MANAGING INPUT AND OUTPUT OPERATIONS IN C    MRS.SOWMYA JYOTHI.pdfMANAGING INPUT AND OUTPUT OPERATIONS IN C    MRS.SOWMYA JYOTHI.pdf
MANAGING INPUT AND OUTPUT OPERATIONS IN C MRS.SOWMYA JYOTHI.pdf
 
C Pointers
C PointersC Pointers
C Pointers
 
Pointers
PointersPointers
Pointers
 
Formatted input and output
Formatted input and outputFormatted input and output
Formatted input and output
 
Constructors and Destructor in C++
Constructors and Destructor in C++Constructors and Destructor in C++
Constructors and Destructor in C++
 
Function in c program
Function in c programFunction in c program
Function in c program
 
String C Programming
String C ProgrammingString C Programming
String C Programming
 
Function overloading
Function overloadingFunction overloading
Function overloading
 
C Structures and Unions
C Structures and UnionsC Structures and Unions
C Structures and Unions
 
Pointer in c
Pointer in cPointer in c
Pointer in c
 
Declaration of variables
Declaration of variablesDeclaration of variables
Declaration of variables
 
Pointer in C
Pointer in CPointer in C
Pointer in C
 
Programming in c Arrays
Programming in c ArraysProgramming in c Arrays
Programming in c Arrays
 
Managing input and output operation in c
Managing input and output operation in cManaging input and output operation in c
Managing input and output operation in c
 
C programming - Pointers
C programming - PointersC programming - Pointers
C programming - Pointers
 
Typedef
TypedefTypedef
Typedef
 

Similar a PPS Notes Unit 5.pdf

Similar a PPS Notes Unit 5.pdf (20)

Unit5
Unit5Unit5
Unit5
 
File Handling in C Programming
File Handling in C ProgrammingFile Handling in C Programming
File Handling in C Programming
 
Module 03 File Handling in C
Module 03 File Handling in CModule 03 File Handling in C
Module 03 File Handling in C
 
File handling in c language
File handling in c languageFile handling in c language
File handling in c language
 
Unit5 C
Unit5 C Unit5 C
Unit5 C
 
Unit5 (2)
Unit5 (2)Unit5 (2)
Unit5 (2)
 
C Language Unit-5
C Language Unit-5C Language Unit-5
C Language Unit-5
 
L8 file
L8 fileL8 file
L8 file
 
C
CC
C
 
Programming in C
Programming in CProgramming in C
Programming in C
 
file_handling_in_c.ppt
file_handling_in_c.pptfile_handling_in_c.ppt
file_handling_in_c.ppt
 
5 Structure & File.pptx
5 Structure & File.pptx5 Structure & File.pptx
5 Structure & File.pptx
 
Data Structure Using C - FILES
Data Structure Using C - FILESData Structure Using C - FILES
Data Structure Using C - FILES
 
CInputOutput.ppt
CInputOutput.pptCInputOutput.ppt
CInputOutput.ppt
 
IN C LANGUAGE- I've been trying to finish this program for the last fe.docx
IN C LANGUAGE- I've been trying to finish this program for the last fe.docxIN C LANGUAGE- I've been trying to finish this program for the last fe.docx
IN C LANGUAGE- I've been trying to finish this program for the last fe.docx
 
File handling in C
File handling in CFile handling in C
File handling in C
 
file_handling_in_c.ppt
file_handling_in_c.pptfile_handling_in_c.ppt
file_handling_in_c.ppt
 
File handling With Solve Programs
File handling With Solve ProgramsFile handling With Solve Programs
File handling With Solve Programs
 
C UNIT-5 PREPARED BY M V BRAHMANANDA REDDY
C UNIT-5 PREPARED BY M V BRAHMANANDA REDDYC UNIT-5 PREPARED BY M V BRAHMANANDA REDDY
C UNIT-5 PREPARED BY M V BRAHMANANDA REDDY
 
File_Handling in C.ppt
File_Handling in C.pptFile_Handling in C.ppt
File_Handling in C.ppt
 

Más de Sreedhar Chowdam

Design and Analysis of Algorithms Lecture Notes
Design and Analysis of Algorithms Lecture NotesDesign and Analysis of Algorithms Lecture Notes
Design and Analysis of Algorithms Lecture NotesSreedhar Chowdam
 
Design and Analysis of Algorithms (Knapsack Problem)
Design and Analysis of Algorithms (Knapsack Problem)Design and Analysis of Algorithms (Knapsack Problem)
Design and Analysis of Algorithms (Knapsack Problem)Sreedhar Chowdam
 
DCCN Network Layer congestion control TCP
DCCN Network Layer congestion control TCPDCCN Network Layer congestion control TCP
DCCN Network Layer congestion control TCPSreedhar Chowdam
 
Data Communication and Computer Networks
Data Communication and Computer NetworksData Communication and Computer Networks
Data Communication and Computer NetworksSreedhar Chowdam
 
Data Communication & Computer Networks
Data Communication & Computer NetworksData Communication & Computer Networks
Data Communication & Computer NetworksSreedhar Chowdam
 
Python Programming: Lists, Modules, Exceptions
Python Programming: Lists, Modules, ExceptionsPython Programming: Lists, Modules, Exceptions
Python Programming: Lists, Modules, ExceptionsSreedhar Chowdam
 
Python Programming by Dr. C. Sreedhar.pdf
Python Programming by Dr. C. Sreedhar.pdfPython Programming by Dr. C. Sreedhar.pdf
Python Programming by Dr. C. Sreedhar.pdfSreedhar Chowdam
 
Python Programming Strings
Python Programming StringsPython Programming Strings
Python Programming StringsSreedhar Chowdam
 
C Recursion, Pointers, Dynamic memory management
C Recursion, Pointers, Dynamic memory managementC Recursion, Pointers, Dynamic memory management
C Recursion, Pointers, Dynamic memory managementSreedhar Chowdam
 
Programming For Problem Solving Lecture Notes
Programming For Problem Solving Lecture NotesProgramming For Problem Solving Lecture Notes
Programming For Problem Solving Lecture NotesSreedhar Chowdam
 
Data Structures Notes 2021
Data Structures Notes 2021Data Structures Notes 2021
Data Structures Notes 2021Sreedhar Chowdam
 
Computer Networks Lecture Notes 01
Computer Networks Lecture Notes 01Computer Networks Lecture Notes 01
Computer Networks Lecture Notes 01Sreedhar Chowdam
 
Dbms university library database
Dbms university library databaseDbms university library database
Dbms university library databaseSreedhar Chowdam
 
Er diagram for library database
Er diagram for library databaseEr diagram for library database
Er diagram for library databaseSreedhar Chowdam
 

Más de Sreedhar Chowdam (20)

Design and Analysis of Algorithms Lecture Notes
Design and Analysis of Algorithms Lecture NotesDesign and Analysis of Algorithms Lecture Notes
Design and Analysis of Algorithms Lecture Notes
 
Design and Analysis of Algorithms (Knapsack Problem)
Design and Analysis of Algorithms (Knapsack Problem)Design and Analysis of Algorithms (Knapsack Problem)
Design and Analysis of Algorithms (Knapsack Problem)
 
DCCN Network Layer congestion control TCP
DCCN Network Layer congestion control TCPDCCN Network Layer congestion control TCP
DCCN Network Layer congestion control TCP
 
Data Communication and Computer Networks
Data Communication and Computer NetworksData Communication and Computer Networks
Data Communication and Computer Networks
 
DCCN Unit 1.pdf
DCCN Unit 1.pdfDCCN Unit 1.pdf
DCCN Unit 1.pdf
 
Data Communication & Computer Networks
Data Communication & Computer NetworksData Communication & Computer Networks
Data Communication & Computer Networks
 
Big Data Analytics Part2
Big Data Analytics Part2Big Data Analytics Part2
Big Data Analytics Part2
 
Python Programming: Lists, Modules, Exceptions
Python Programming: Lists, Modules, ExceptionsPython Programming: Lists, Modules, Exceptions
Python Programming: Lists, Modules, Exceptions
 
Python Programming by Dr. C. Sreedhar.pdf
Python Programming by Dr. C. Sreedhar.pdfPython Programming by Dr. C. Sreedhar.pdf
Python Programming by Dr. C. Sreedhar.pdf
 
Python Programming Strings
Python Programming StringsPython Programming Strings
Python Programming Strings
 
Python Programming
Python Programming Python Programming
Python Programming
 
Python Programming
Python ProgrammingPython Programming
Python Programming
 
C Recursion, Pointers, Dynamic memory management
C Recursion, Pointers, Dynamic memory managementC Recursion, Pointers, Dynamic memory management
C Recursion, Pointers, Dynamic memory management
 
Programming For Problem Solving Lecture Notes
Programming For Problem Solving Lecture NotesProgramming For Problem Solving Lecture Notes
Programming For Problem Solving Lecture Notes
 
Big Data Analytics
Big Data AnalyticsBig Data Analytics
Big Data Analytics
 
Data Structures Notes 2021
Data Structures Notes 2021Data Structures Notes 2021
Data Structures Notes 2021
 
Computer Networks Lecture Notes 01
Computer Networks Lecture Notes 01Computer Networks Lecture Notes 01
Computer Networks Lecture Notes 01
 
Dbms university library database
Dbms university library databaseDbms university library database
Dbms university library database
 
Er diagram for library database
Er diagram for library databaseEr diagram for library database
Er diagram for library database
 
Dbms ER Model
Dbms ER ModelDbms ER Model
Dbms ER Model
 

Último

Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.eptoze12
 
Risk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdfRisk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdfROCENODodongVILLACER
 
Concrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptxConcrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptxKartikeyaDwivedi3
 
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionSachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionDr.Costas Sachpazis
 
IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024Mark Billinghurst
 
Heart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxHeart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxPoojaBan
 
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)dollysharma2066
 
Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...VICTOR MAESTRE RAMIREZ
 
Past, Present and Future of Generative AI
Past, Present and Future of Generative AIPast, Present and Future of Generative AI
Past, Present and Future of Generative AIabhishek36461
 
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)Dr SOUNDIRARAJ N
 
Call Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile serviceCall Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile servicerehmti665
 
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdfCCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdfAsst.prof M.Gokilavani
 
What are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxWhat are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxwendy cai
 
An experimental study in using natural admixture as an alternative for chemic...
An experimental study in using natural admixture as an alternative for chemic...An experimental study in using natural admixture as an alternative for chemic...
An experimental study in using natural admixture as an alternative for chemic...Chandu841456
 

Último (20)

Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.
 
Risk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdfRisk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdf
 
Concrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptxConcrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptx
 
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionSachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
 
IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024
 
Heart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxHeart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptx
 
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
 
Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...
 
Past, Present and Future of Generative AI
Past, Present and Future of Generative AIPast, Present and Future of Generative AI
Past, Present and Future of Generative AI
 
Design and analysis of solar grass cutter.pdf
Design and analysis of solar grass cutter.pdfDesign and analysis of solar grass cutter.pdf
Design and analysis of solar grass cutter.pdf
 
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
 
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
 
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCRCall Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
 
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Serviceyoung call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
 
Call Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile serviceCall Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile service
 
POWER SYSTEMS-1 Complete notes examples
POWER SYSTEMS-1 Complete notes  examplesPOWER SYSTEMS-1 Complete notes  examples
POWER SYSTEMS-1 Complete notes examples
 
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
 
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdfCCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
 
What are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxWhat are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptx
 
An experimental study in using natural admixture as an alternative for chemic...
An experimental study in using natural admixture as an alternative for chemic...An experimental study in using natural admixture as an alternative for chemic...
An experimental study in using natural admixture as an alternative for chemic...
 

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); }
  • 9.
  • 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 ”);