SlideShare une entreprise Scribd logo
1  sur  24
Dynamic Memory Allocation
The process of allocating memory at run time is
known as dynamic memory allocation. Although c
does not inherently have this facility there are four
library routines which allow this functions, which can
be used to allocate and free memory during the
program execution.
Dynamic Memory Allocation Functions
malloc()
A block mf memory may be allocated using the
function malloc. The malloc function reserves a block
of memory of specified size and returns a pointer of
type void. This means that we can assign it to any
type of pointer. It takes the following form:
ptr=(cast-type*)malloc(byte-size);
ptr is a pointer of type cast-type the malloc
returns a pointer (of cast type) to an area of
memory with size byte-size
malloc() Example
Example:
x=(int*)malloc(100*sizeof(int));
On successful execution of this statement a memory
equivalent to 100 times the area of int bytes is
reserved and the address of the first byte of
memory allocated is assigned to the pointer x of
type int.
Calloc
Calloc is another memory allocation function that is
normally used to request multiple blocks of storage
each of the same size and then sets all bytes to zero.
The general form of calloc is:
ptr=(cast-type*) calloc(n,elem-size);
Calloc(Contd.)
calloc() allocates contiguous space for n blocks each
size of elements size bytes. All bytes are initialized to
zero and a pointer to the first byte of the allocated
region is returned. If there is not enough space a null
pointer is returned.
free()
Compile time storage of a variable is allocated and
released by the system in accordance with its storage
class. With the dynamic runtime allocation, it is our
responsibility to release the space when it is not
required.
free(ptr);
ptr is a pointer that has been created by using malloc
or calloc
realloc
The memory allocated by using calloc or malloc might
be insufficient or excess sometimes in both the
situations we can change the memory size already
allocated with the help of the function realloc. This
process is called reallocation of memory. The general
statement of reallocation of memory is :
ptr=realloc(ptr,newsize);
FILE HANDLING
Introduction
Files are places where data can be stored
permanently.
Some programs expect the same set of data to be
fed as input every time it is run.
Cumbersome.
Better if the data are kept in a file, and the program
reads from the file.
Programs generating large volumes of output.
Difficult to view on the screen.
Better to store them in a file for later viewing/
processing
Basic File Operations
Opening a file
Reading data from a file
Writing data to a file
Closing a file
Opening a File
A file must be “opened” before it can be used.
FILE *fp;
:
fp = fopen (filename, mode);
fp is declared as a pointer to the data type FILE.
filename is a string - specifies the name of the file.
fopen returns a pointer to the file which is used in all
subsequent file operations.
mode is a string which specifies the purpose of opening
the file:
“r” :: open the file for reading only
“w” :: open the file for writing only
“a” :: open the file for appending data to it
Closing a File
After all operations on a file have been
completed, it must be closed.
Ensures that all file data stored in memory buffers are
properly written to the file.
General format: fclose (file_pointer) ;
FILE *xyz ;
xyz = fopen (“test”, “w”) ;
…….
fclose (xyz) ;
Read/Write Operations on Files
The simplest file input-output (I/O) function are getc and
putc.
getc is used to read a character from a file and return it.
char ch; FILE *fp;
…..
ch = getc (fp) ;
getc will return an end-of-file marker EOF, when the end of the
file has been reached.
putc is used to write a character to a file.
char ch; FILE *fp;
……
putc (c, fp) ;
main() {
FILE *in, *out ;
char c ;
in = fopen (“infile.dat”, “r”) ;
out = fopen (“outfile.dat”, “w”) ;
while ((c = getc (in)) != EOF)
putc (toupper (c), out);
fclose (in) ;
fclose (out) ;
}
Basic operations of files(Contd.)
We can also use the file versions of scanf and printf,
called fscanf and fprintf.
General format:
fscanf (file_pointer, control_string, list) ;
fprintf (file_pointer, control_string, list) ;
Examples:
fscanf (fp, “%d %s %f”, &roll, dept_code, &cgpa) ;
fprintf (out, “nThe result is: %d”, xyz) ;
Command line argument
Command line arguments are parameters supplied to a
program, when the program is invoked.
How do these parameters get into the program?
Every C program has a main function.
main can take two arguments conventionally called argc and
argv.
Information regarding command line arguments are passed to
the program through argc and argv.
INTRODUCTION TO C
PREPROCESSOR
C Preprocessor
Overview
Preprocessor Directives
Conditional Compilation
Overview
 Six phases to execute C:
1. Edit
2. Preprocess
3. Compile
4. Link
5. Load
6. Execute
C Preprocessor
All preprocessor directives begin with #
Possible actions
Inclusion of other files
Definition of symbolic constants & macros
Conditional compilation of program code
Conditional compilation of preprocessor directives
Preprocessor Directives
#define for symbolic constants
#define identifier text
 Creates symbolic constants
 The “identifier” is replaced by “text” in the program
Example
#define PI 3.14
area = PI * radius * radius;
 Replaced by “area = 3.14 * radius * radius” by
preprocessor before compilation
Conditional Compilation
Controls the execution of preprocessor directives
& compilation of code
Define NULL, if it hasn’t been defined yet
#if !defined(NULL)
#define NULL 0
#endif
Use to comment out code (for comments)
#if 0
code prevented from compiling
#endif
THANK YOU

Contenu connexe

Tendances

Structures in c language
Structures in c languageStructures in c language
Structures in c languagetanmaymodi4
 
Dynamic memory allocation in c++
Dynamic memory allocation in c++Dynamic memory allocation in c++
Dynamic memory allocation in c++Tech_MX
 
Data Types - Premetive and Non Premetive
Data Types - Premetive and Non Premetive Data Types - Premetive and Non Premetive
Data Types - Premetive and Non Premetive Raj Naik
 
Presentation on c structures
Presentation on c   structures Presentation on c   structures
Presentation on c structures topu93
 
File handling in c
File handling in cFile handling in c
File handling in caakanksha s
 
Manipulators in c++
Manipulators in c++Manipulators in c++
Manipulators in c++Ashok Raj
 
Functions in c language
Functions in c language Functions in c language
Functions in c language tanmaymodi4
 
Oop c++class(final).ppt
Oop c++class(final).pptOop c++class(final).ppt
Oop c++class(final).pptAlok Kumar
 

Tendances (20)

Pointers C programming
Pointers  C programmingPointers  C programming
Pointers C programming
 
Pointer in c
Pointer in cPointer in c
Pointer in c
 
Structure in C language
Structure in C languageStructure in C language
Structure in C language
 
Instruction format
Instruction formatInstruction format
Instruction format
 
Structure in C
Structure in CStructure in C
Structure in C
 
Pointers in c++
Pointers in c++Pointers in c++
Pointers in c++
 
Structures in c language
Structures in c languageStructures in c language
Structures in c language
 
Dynamic memory allocation in c++
Dynamic memory allocation in c++Dynamic memory allocation in c++
Dynamic memory allocation in c++
 
Array Of Pointers
Array Of PointersArray Of Pointers
Array Of Pointers
 
Data Types - Premetive and Non Premetive
Data Types - Premetive and Non Premetive Data Types - Premetive and Non Premetive
Data Types - Premetive and Non Premetive
 
Presentation on c structures
Presentation on c   structures Presentation on c   structures
Presentation on c structures
 
File handling in c
File handling in cFile handling in c
File handling in c
 
Manipulators in c++
Manipulators in c++Manipulators in c++
Manipulators in c++
 
Function Pointer
Function PointerFunction Pointer
Function Pointer
 
C Programming Unit-5
C Programming Unit-5C Programming Unit-5
C Programming Unit-5
 
Programming in c Arrays
Programming in c ArraysProgramming in c Arrays
Programming in c Arrays
 
Function C programming
Function C programmingFunction C programming
Function C programming
 
Functions in c language
Functions in c language Functions in c language
Functions in c language
 
File handling in c
File handling in cFile handling in c
File handling in c
 
Oop c++class(final).ppt
Oop c++class(final).pptOop c++class(final).ppt
Oop c++class(final).ppt
 

Similaire à Memory allocation in c

EASY UNDERSTANDING OF FILES IN C LANGUAGE.pdf
EASY UNDERSTANDING OF FILES IN C LANGUAGE.pdfEASY UNDERSTANDING OF FILES IN C LANGUAGE.pdf
EASY UNDERSTANDING OF FILES IN C LANGUAGE.pdfsudhakargeruganti
 
Module 03 File Handling in C
Module 03 File Handling in CModule 03 File Handling in C
Module 03 File Handling in CTushar B Kute
 
Data Structure Using C - FILES
Data Structure Using C - FILESData Structure Using C - FILES
Data Structure Using C - FILESHarish Kamat
 
File Management in C
File Management in CFile Management in C
File Management in CPaurav Shah
 
C library for input output operations.cstdio.(stdio.h)
C library for input output operations.cstdio.(stdio.h)C library for input output operations.cstdio.(stdio.h)
C library for input output operations.cstdio.(stdio.h)leonard horobet-stoian
 
Unit_V_Files handling in c programming language.pptx
Unit_V_Files handling in c programming language.pptxUnit_V_Files handling in c programming language.pptx
Unit_V_Files handling in c programming language.pptxraushankumarthakur7
 
Concept of file handling in c
Concept of file handling in cConcept of file handling in c
Concept of file handling in cMugdhaSharma11
 
File management
File managementFile management
File managementsumathiv9
 
Advance C Programming UNIT 4-FILE HANDLING IN C.pdf
Advance C Programming UNIT 4-FILE HANDLING IN C.pdfAdvance C Programming UNIT 4-FILE HANDLING IN C.pdf
Advance C Programming UNIT 4-FILE HANDLING IN C.pdfsangeeta borde
 
File Handling in C Programming
File Handling in C ProgrammingFile Handling in C Programming
File Handling in C ProgrammingRavindraSalunke3
 

Similaire à Memory allocation in c (20)

File mangement
File mangementFile mangement
File mangement
 
File management
File managementFile management
File management
 
Unit5
Unit5Unit5
Unit5
 
EASY UNDERSTANDING OF FILES IN C LANGUAGE.pdf
EASY UNDERSTANDING OF FILES IN C LANGUAGE.pdfEASY UNDERSTANDING OF FILES IN C LANGUAGE.pdf
EASY UNDERSTANDING OF FILES IN C LANGUAGE.pdf
 
File Handling in C
File Handling in CFile Handling in C
File Handling in C
 
Module 03 File Handling in C
Module 03 File Handling in CModule 03 File Handling in C
Module 03 File Handling in C
 
Data Structure Using C - FILES
Data Structure Using C - FILESData Structure Using C - FILES
Data Structure Using C - FILES
 
Unit5 C
Unit5 C Unit5 C
Unit5 C
 
Handout#01
Handout#01Handout#01
Handout#01
 
File Management in C
File Management in CFile Management in C
File Management in C
 
File in c
File in cFile in c
File in c
 
File Handling in C.pptx
File Handling in C.pptxFile Handling in C.pptx
File Handling in C.pptx
 
C library for input output operations.cstdio.(stdio.h)
C library for input output operations.cstdio.(stdio.h)C library for input output operations.cstdio.(stdio.h)
C library for input output operations.cstdio.(stdio.h)
 
File handling in C
File handling in CFile handling in C
File handling in C
 
File management
File managementFile management
File management
 
Unit_V_Files handling in c programming language.pptx
Unit_V_Files handling in c programming language.pptxUnit_V_Files handling in c programming language.pptx
Unit_V_Files handling in c programming language.pptx
 
Concept of file handling in c
Concept of file handling in cConcept of file handling in c
Concept of file handling in c
 
File management
File managementFile management
File management
 
Advance C Programming UNIT 4-FILE HANDLING IN C.pdf
Advance C Programming UNIT 4-FILE HANDLING IN C.pdfAdvance C Programming UNIT 4-FILE HANDLING IN C.pdf
Advance C Programming UNIT 4-FILE HANDLING IN C.pdf
 
File Handling in C Programming
File Handling in C ProgrammingFile Handling in C Programming
File Handling in C Programming
 

Plus de Prabhu Govind

Plus de Prabhu Govind (20)

Preprocessor in C
Preprocessor in CPreprocessor in C
Preprocessor in C
 
Pointers in C
Pointers in CPointers in C
Pointers in C
 
Unions in c
Unions in cUnions in c
Unions in c
 
Structure in c
Structure in cStructure in c
Structure in c
 
Array & string
Array & stringArray & string
Array & string
 
Recursive For S-Teacher
Recursive For S-TeacherRecursive For S-Teacher
Recursive For S-Teacher
 
User defined Functions in C
User defined Functions in CUser defined Functions in C
User defined Functions in C
 
Pre defined Functions in C
Pre defined Functions in CPre defined Functions in C
Pre defined Functions in C
 
Looping in C
Looping in CLooping in C
Looping in C
 
Branching in C
Branching in CBranching in C
Branching in C
 
Types of operators in C
Types of operators in CTypes of operators in C
Types of operators in C
 
Operators in C
Operators in COperators in C
Operators in C
 
Statements in C
Statements in CStatements in C
Statements in C
 
Data types in C
Data types in CData types in C
Data types in C
 
Constants in C
Constants in CConstants in C
Constants in C
 
Variables_c
Variables_cVariables_c
Variables_c
 
Tokens_C
Tokens_CTokens_C
Tokens_C
 
Computer basics
Computer basicsComputer basics
Computer basics
 
Computer fundamentals
Computer fundamentalsComputer fundamentals
Computer fundamentals
 
computer hardware and software
computer hardware and softwarecomputer hardware and software
computer hardware and software
 

Dernier

1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Disha Kariya
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfchloefrazer622
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room servicediscovermytutordmt
 
General AI for Medical Educators April 2024
General AI for Medical Educators April 2024General AI for Medical Educators April 2024
General AI for Medical Educators April 2024Janet Corral
 
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...PsychoTech Services
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingTeacherCyreneCayanan
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...fonyou31
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfagholdier
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 

Dernier (20)

Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Advance Mobile Application Development class 07
Advance Mobile Application Development class 07
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdf
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room service
 
General AI for Medical Educators April 2024
General AI for Medical Educators April 2024General AI for Medical Educators April 2024
General AI for Medical Educators April 2024
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writing
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 

Memory allocation in c

  • 1. Dynamic Memory Allocation The process of allocating memory at run time is known as dynamic memory allocation. Although c does not inherently have this facility there are four library routines which allow this functions, which can be used to allocate and free memory during the program execution.
  • 3. malloc() A block mf memory may be allocated using the function malloc. The malloc function reserves a block of memory of specified size and returns a pointer of type void. This means that we can assign it to any type of pointer. It takes the following form: ptr=(cast-type*)malloc(byte-size); ptr is a pointer of type cast-type the malloc returns a pointer (of cast type) to an area of memory with size byte-size
  • 4. malloc() Example Example: x=(int*)malloc(100*sizeof(int)); On successful execution of this statement a memory equivalent to 100 times the area of int bytes is reserved and the address of the first byte of memory allocated is assigned to the pointer x of type int.
  • 5. Calloc Calloc is another memory allocation function that is normally used to request multiple blocks of storage each of the same size and then sets all bytes to zero. The general form of calloc is: ptr=(cast-type*) calloc(n,elem-size);
  • 6. Calloc(Contd.) calloc() allocates contiguous space for n blocks each size of elements size bytes. All bytes are initialized to zero and a pointer to the first byte of the allocated region is returned. If there is not enough space a null pointer is returned.
  • 7. free() Compile time storage of a variable is allocated and released by the system in accordance with its storage class. With the dynamic runtime allocation, it is our responsibility to release the space when it is not required. free(ptr); ptr is a pointer that has been created by using malloc or calloc
  • 8. realloc The memory allocated by using calloc or malloc might be insufficient or excess sometimes in both the situations we can change the memory size already allocated with the help of the function realloc. This process is called reallocation of memory. The general statement of reallocation of memory is : ptr=realloc(ptr,newsize);
  • 10. Introduction Files are places where data can be stored permanently. Some programs expect the same set of data to be fed as input every time it is run. Cumbersome. Better if the data are kept in a file, and the program reads from the file. Programs generating large volumes of output. Difficult to view on the screen. Better to store them in a file for later viewing/ processing
  • 11. Basic File Operations Opening a file Reading data from a file Writing data to a file Closing a file
  • 12. Opening a File A file must be “opened” before it can be used. FILE *fp; : fp = fopen (filename, mode); fp is declared as a pointer to the data type FILE. filename is a string - specifies the name of the file. fopen returns a pointer to the file which is used in all subsequent file operations. mode is a string which specifies the purpose of opening the file: “r” :: open the file for reading only “w” :: open the file for writing only “a” :: open the file for appending data to it
  • 13. Closing a File After all operations on a file have been completed, it must be closed. Ensures that all file data stored in memory buffers are properly written to the file. General format: fclose (file_pointer) ; FILE *xyz ; xyz = fopen (“test”, “w”) ; ……. fclose (xyz) ;
  • 14. Read/Write Operations on Files The simplest file input-output (I/O) function are getc and putc. getc is used to read a character from a file and return it. char ch; FILE *fp; ….. ch = getc (fp) ; getc will return an end-of-file marker EOF, when the end of the file has been reached. putc is used to write a character to a file. char ch; FILE *fp; …… putc (c, fp) ;
  • 15. main() { FILE *in, *out ; char c ; in = fopen (“infile.dat”, “r”) ; out = fopen (“outfile.dat”, “w”) ; while ((c = getc (in)) != EOF) putc (toupper (c), out); fclose (in) ; fclose (out) ; }
  • 16. Basic operations of files(Contd.) We can also use the file versions of scanf and printf, called fscanf and fprintf. General format: fscanf (file_pointer, control_string, list) ; fprintf (file_pointer, control_string, list) ; Examples: fscanf (fp, “%d %s %f”, &roll, dept_code, &cgpa) ; fprintf (out, “nThe result is: %d”, xyz) ;
  • 17. Command line argument Command line arguments are parameters supplied to a program, when the program is invoked. How do these parameters get into the program? Every C program has a main function. main can take two arguments conventionally called argc and argv. Information regarding command line arguments are passed to the program through argc and argv.
  • 20. Overview  Six phases to execute C: 1. Edit 2. Preprocess 3. Compile 4. Link 5. Load 6. Execute
  • 21. C Preprocessor All preprocessor directives begin with # Possible actions Inclusion of other files Definition of symbolic constants & macros Conditional compilation of program code Conditional compilation of preprocessor directives
  • 22. Preprocessor Directives #define for symbolic constants #define identifier text  Creates symbolic constants  The “identifier” is replaced by “text” in the program Example #define PI 3.14 area = PI * radius * radius;  Replaced by “area = 3.14 * radius * radius” by preprocessor before compilation
  • 23. Conditional Compilation Controls the execution of preprocessor directives & compilation of code Define NULL, if it hasn’t been defined yet #if !defined(NULL) #define NULL 0 #endif Use to comment out code (for comments) #if 0 code prevented from compiling #endif