SlideShare a Scribd company logo
1 of 6
Download to read offline
[Type the document title]
Compiled & Edited by: Prof. L. Krishnananda, HOD, Dept of ECE, GSKSJTI, Bengaluru Page 1
File Operations in C:
 In C, we use a FILE * data type to access files.
 FILE * is defined in /usr/include/stdio.h
An example:
#include <stdio.h>
int main( )
{
FILE *fp; // create a pointer of type FILE
fp = fopen("tmp.txt", "w");
fprintf (fp,"This is a testn");
fclose(fp);
return 0;
}
4.6.1 Opening a File:
You must include <stdio.h>
Prototype Form:
FILE * fopen (const char * filename, const char * mode)
FILE is a structure type declared in stdio.h.
– No need to know the details of the structure.
– fopen returns a pointer to the FILE structure type.
– You must declare a pointer of type FILE to receive that value when it is returned.
– Use the returned pointer in all subsequent references to that file.
– If fopen fails, NULL is returned.
The argument filename is the name of the file to be opened.
Values of mode:
Enclose in double quotes or pass as a string variable
Modes:
r: open the file for reading (NULL if it doesn’t exist)
w: create for writing. destroy old if file exists
a: open for writing. create if not there. start at the end-of-file
r+: open for update (r/w). create if not there. start at the beginning.
w+: create for r/w. destroy old if there
a+: open for r/w. create if not there. start at the end-of-file
In the text book, there are other binary modes with the letter b. They have no effect in today’s C
compilers.
4.6.2 Stdin, stdout, stderr:
 Every C program has three files opened for them at start-up: stdin, stdout, and stderr
 stdin is opened for reading, while stdout and stderr are opened for writing
 They can be used wherever a FILE * can be used.
Examples:
– fprintf (stdout, "Hello there!n");
This is the same as printf("Hello there!n");
– fscanf (stdin, "%d", &int_var);
This is the same as scanf("%d", &int_var);
– fprintf (stderr, "An error has occurred!n");
This is useful to report errors to standard error - it flushes output as well, so
this is really good for debugging!
[Type the document title]
Compiled & Edited by: Prof. L. Krishnananda, HOD, Dept of ECE, GSKSJTI, Bengaluru Page 2
4.6.3 The exit ( ) function:
This is used to leave the program at anytime from anywhere before the “normal” exit location.
Syntax:
exit (status);
Example:
#include <stdlib.h>
……
if( (fp=fopen("a.txt","r")) == NULL)
{
fprintf(stderr, "Cannot open file a.txt!n");
exit (1);
}
Four ways to Read and Write Files:
 Formatted file I/O
 Get and put a character
 Get and put a line
 Block read and write
4.7.1 Formatted File I/O:
Formatted File input is done through fscanf:
– int fscanf (FILE * fp, const char * fmt, ...) ;
Formatted File output is done through fprintf:
– int fprintf(FILE *fp, const char *fmt, …);
{
FILE *fp1, *fp2;
int n;
fp1 = fopen ("file1", "r");
fp2 = fopen ("file2", "w");
fscanf (fp1, "%d", &n);
fprint f(fp2, "%d", n);
fclose (fp1);
fclose (fp2);
}
4.7.2 Get & Put a Character:
#include <stdio.h>
int fgetc (FILE * fp);
int fputc (int c, FILE * fp);
These two functions read or write a single byte from or to a file.
 fgetc returns the character that was read, converted to an integer.
 fputc returns the same value of parameter c if it succeeds, otherwise, return EOF.
4.7.3 Get & Put a Line:
#include <stdio.h>
char *fgets(char *s, int n, FILE * fp);
int fputs (char *s, FILE * fp);
These two functions read or write a string from or to a file.
[Type the document title]
Compiled & Edited by: Prof. L. Krishnananda, HOD, Dept of ECE, GSKSJTI, Bengaluru Page 3
 gets reads an entire line into s, up to n-1 characters in length (pass the size of the character
array s in as n to be safe!)
 fgets returns the pointer s on success, or NULL if an error or end-of-file is reached.
 fputs returns the number of characters written if successful; otherwise, return EOF.
4.7.4 fwrite and fread
fread and fwrite are binary file reading and writing functions
– Prototypes are found in stdio.h
Generic Form:
int fwrite (void *buf, int size, int count, FILE *fp) ;
int fread (void *buf, int size, int count, FILE *fp) ;
buf: is a pointer to the region in memory to be written/read
– It can be a pointer to anything
size: the size in bytes of each individual data item
count: the number of data items to be written/read
For example, a 100 element array of integers can be written as
– fwrite( buf, sizeof(int), 100, fp);
The fwrite (fread) returns the number of items actually written (read).
Testing for errors:
if ((frwrite (buf, size, count, fp)) != count)
fprintf (stderr, "Error writing to file.");
Writing a single double variable x to a file:
fwrite (&x, sizeof(double), 1, fp) ;
This writes the double x to the file in raw binary format. i.e., it simply writes the
internal machine format of x
Writing an array text[50] of 50 characters can be done by:
– fwrite (text, sizeof (char), 50, fp) ;
or
– fwrite (text, sizeof(text), 1, fp); /* text must be a local array name */
Note: fread and frwrite are more efficient than fscanf and fprintf
4.7.5 Closing and Flushing Files:
Syntax:
int fclose (FILE * fp) ;
closes fp -- returns 0 if it works -1 if it fails
You can clear a buffer without closing it
int fflush (FILE * fp) ;
Essentially this is a force to disk.
Very useful when debugging.
Without fclose or fflush, your updates to a file may not be written to the file on disk. (Operating
systems like Unix usually use “write caching” disk access.)
4.7.6 Detecting end of File:
Text mode files:
while ( (c = fgetc (fp) ) != EOF )
– Reads characters until it encounters the EOF
– The problem is that the byte of data read may not be distinguishable from EOF.
[Type the document title]
Compiled & Edited by: Prof. L. Krishnananda, HOD, Dept of ECE, GSKSJTI, Bengaluru Page 4
Binary mode files:
int feof (FILE * fp) ;
– Note: the feof function realizes the end of file only after a reading failed (fread,
fscanf, fgetc … )
fseek (fp,0,SEEK_END);
printf ("%dn", feof(fp)); /* zero value */
fgetc (fp); /* fgetc returns -1 */
printf("%dn",feof(fp)); /* nonzero value */
Example:
#define BUFSIZE 100
int main ( )
{
char buf[BUFSIZE];
if ( (fp=fopen("file1", "r"))==NULL)
{
fprintf (stderr,"Error opening file.");
exit (1);
}
while (!feof(fp)) {
fgets (buf, BUFSIZE, fp);
printf ("%s",buf);
} // end of while
fclose (fp);
return 0;
} // end of main
[Type the document title]
Compiled & Edited by: Prof. L. Krishnananda, HOD, Dept of ECE, GSKSJTI, Bengaluru Page 5
The fgets() function meets the possible overflow problem by taking as second argument that limits
the number of characters to be read. This function is designed for file input, which makes it a little
more awkward to use. Here is how fgets() differs from gets():
1.It takes a second argument indicating the maximum number of characters to read. If this argument
has the value n , fgets()reads up to n-1 characters or through the newline character, whichever comes
first.
2.If fgets()reads the newline, it stores it in the string, unlike gets(), which discards it.
3.It takes a third argument indicating which file to read. To read from the keyboard, use stdin(for
standard input ) as the argument; this identifier is defined in stdio.h.
fputs() function:
•It takes a string argument then prints it without adding a newline.
#include <stdio.h>
#define STLEN 14
int main(void)
{
char words[STLEN];
puts("Enter a string, please.");
fgets(words, STLEN, stdin);
printf("Your string twice (puts(), then fputs()):n");
puts(words);
fputs(words, stdout);
puts("Enter another string, please.");
fgets(words, STLEN, stdin);
printf("Your string twice (puts(), then fputs()):n");
puts(words);
fputs(words, stdout);
[Type the document title]
Compiled & Edited by: Prof. L. Krishnananda, HOD, Dept of ECE, GSKSJTI, Bengaluru Page 6
puts("Done.");
return0;
}
Output
Enter a string, please.
applegrapes
Your string twice (puts(), thenfputs()):
applegrapes
applegrapes
Enter another string,please.
strawberryshortcake
Your string twice (puts(),thenfputs()):
strawberryshstrawberryshDone.

More Related Content

What's hot

Unit5 (2)
Unit5 (2)Unit5 (2)
Unit5 (2)mrecedu
 
File Management in C
File Management in CFile Management in C
File Management in CPaurav Shah
 
Unix systems programming interprocess communication/tutorialoutlet
Unix systems programming interprocess communication/tutorialoutletUnix systems programming interprocess communication/tutorialoutlet
Unix systems programming interprocess communication/tutorialoutletBeaglesz
 
File handling in C
File handling in CFile handling in C
File handling in CRabin BK
 
Understanding c file handling functions with examples
Understanding c file handling functions with examplesUnderstanding c file handling functions with examples
Understanding c file handling functions with examplesMuhammed Thanveer M
 
File handling in c
File handling in cFile handling in c
File handling in cmohit biswal
 
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
 
File handling-dutt
File handling-duttFile handling-dutt
File handling-duttAnil Dutt
 
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
 
File handling in 'C'
File handling in 'C'File handling in 'C'
File handling in 'C'Gaurav Garg
 
Files in C
Files in CFiles in C
Files in CPrabu U
 
File handling-c programming language
File handling-c programming languageFile handling-c programming language
File handling-c programming languagethirumalaikumar3
 
Bt0067 c programming and data structures2
Bt0067 c programming and data structures2Bt0067 c programming and data structures2
Bt0067 c programming and data structures2Techglyphs
 
Programming in C
Programming in CProgramming in C
Programming in Csujathavvv
 

What's hot (18)

File in C language
File in C languageFile in C language
File in C language
 
Unit5 (2)
Unit5 (2)Unit5 (2)
Unit5 (2)
 
File Management in C
File Management in CFile Management in C
File Management in C
 
Unix systems programming interprocess communication/tutorialoutlet
Unix systems programming interprocess communication/tutorialoutletUnix systems programming interprocess communication/tutorialoutlet
Unix systems programming interprocess communication/tutorialoutlet
 
File handling in C
File handling in CFile handling in C
File handling in C
 
Understanding c file handling functions with examples
Understanding c file handling functions with examplesUnderstanding c file handling functions with examples
Understanding c file handling functions with examples
 
File handling in c
File handling in cFile handling in c
File handling in c
 
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-dutt
File handling-duttFile handling-dutt
File handling-dutt
 
C Programming Project
C Programming ProjectC Programming Project
C Programming Project
 
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'
File handling in 'C'File handling in 'C'
File handling in 'C'
 
Files in C
Files in CFiles in C
Files in C
 
Functions in python
Functions in pythonFunctions in python
Functions in python
 
File handling-c programming language
File handling-c programming languageFile handling-c programming language
File handling-c programming language
 
File handling in c
File  handling in cFile  handling in c
File handling in c
 
Bt0067 c programming and data structures2
Bt0067 c programming and data structures2Bt0067 c programming and data structures2
Bt0067 c programming and data structures2
 
Programming in C
Programming in CProgramming in C
Programming in C
 

Similar to Lk module4 file

Similar to Lk module4 file (20)

Handout#01
Handout#01Handout#01
Handout#01
 
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-c
File handling-cFile handling-c
File handling-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.pdf
 
File management
File managementFile management
File management
 
file handling1
file handling1file handling1
file handling1
 
Unit5
Unit5Unit5
Unit5
 
Unit5 C
Unit5 C Unit5 C
Unit5 C
 
Module 5 file cp
Module 5 file cpModule 5 file cp
Module 5 file cp
 
File handling in c
File handling in cFile handling in c
File handling in c
 
C Programming Unit-5
C Programming Unit-5C Programming Unit-5
C Programming Unit-5
 
File Handling in c.ppt
File Handling in c.pptFile Handling in c.ppt
File Handling in c.ppt
 
file_handling_in_c.ppt
file_handling_in_c.pptfile_handling_in_c.ppt
file_handling_in_c.ppt
 
Files_in_C.ppt
Files_in_C.pptFiles_in_C.ppt
Files_in_C.ppt
 
file_handling_in_c.ppt
file_handling_in_c.pptfile_handling_in_c.ppt
file_handling_in_c.ppt
 
C programming session 08
C programming session 08C programming session 08
C programming session 08
 
Satz1
Satz1Satz1
Satz1
 
Chapter 13.1.10
Chapter 13.1.10Chapter 13.1.10
Chapter 13.1.10
 
File in c
File in cFile in c
File in c
 
PPS PPT 2.pptx
PPS PPT 2.pptxPPS PPT 2.pptx
PPS PPT 2.pptx
 

More from Krishna Nanda

Python regular expressions
Python regular expressionsPython regular expressions
Python regular expressionsKrishna Nanda
 
Computer Communication Networks- Introduction to Transport layer
Computer Communication Networks- Introduction to Transport layerComputer Communication Networks- Introduction to Transport layer
Computer Communication Networks- Introduction to Transport layerKrishna Nanda
 
Computer Communication Networks- TRANSPORT LAYER PROTOCOLS
Computer Communication Networks- TRANSPORT LAYER PROTOCOLSComputer Communication Networks- TRANSPORT LAYER PROTOCOLS
Computer Communication Networks- TRANSPORT LAYER PROTOCOLSKrishna Nanda
 
COMPUTER COMMUNICATION NETWORKS -IPv4
COMPUTER COMMUNICATION NETWORKS -IPv4COMPUTER COMMUNICATION NETWORKS -IPv4
COMPUTER COMMUNICATION NETWORKS -IPv4Krishna Nanda
 
COMPUTER COMMUNICATION NETWORKS-R-Routing protocols 2
COMPUTER COMMUNICATION NETWORKS-R-Routing protocols 2COMPUTER COMMUNICATION NETWORKS-R-Routing protocols 2
COMPUTER COMMUNICATION NETWORKS-R-Routing protocols 2Krishna Nanda
 
Computer Communication Networks-Routing protocols 1
Computer Communication Networks-Routing protocols 1Computer Communication Networks-Routing protocols 1
Computer Communication Networks-Routing protocols 1Krishna Nanda
 
Computer Communication Networks-Wireless LAN
Computer Communication Networks-Wireless LANComputer Communication Networks-Wireless LAN
Computer Communication Networks-Wireless LANKrishna Nanda
 
Computer Communication Networks-Network Layer
Computer Communication Networks-Network LayerComputer Communication Networks-Network Layer
Computer Communication Networks-Network LayerKrishna Nanda
 
Lk module4 structures
Lk module4 structuresLk module4 structures
Lk module4 structuresKrishna Nanda
 

More from Krishna Nanda (16)

Python regular expressions
Python regular expressionsPython regular expressions
Python regular expressions
 
Python dictionaries
Python dictionariesPython dictionaries
Python dictionaries
 
Python lists
Python listsPython lists
Python lists
 
Python-Tuples
Python-TuplesPython-Tuples
Python-Tuples
 
Python- strings
Python- stringsPython- strings
Python- strings
 
Python-files
Python-filesPython-files
Python-files
 
Computer Communication Networks- Introduction to Transport layer
Computer Communication Networks- Introduction to Transport layerComputer Communication Networks- Introduction to Transport layer
Computer Communication Networks- Introduction to Transport layer
 
Computer Communication Networks- TRANSPORT LAYER PROTOCOLS
Computer Communication Networks- TRANSPORT LAYER PROTOCOLSComputer Communication Networks- TRANSPORT LAYER PROTOCOLS
Computer Communication Networks- TRANSPORT LAYER PROTOCOLS
 
COMPUTER COMMUNICATION NETWORKS -IPv4
COMPUTER COMMUNICATION NETWORKS -IPv4COMPUTER COMMUNICATION NETWORKS -IPv4
COMPUTER COMMUNICATION NETWORKS -IPv4
 
COMPUTER COMMUNICATION NETWORKS-R-Routing protocols 2
COMPUTER COMMUNICATION NETWORKS-R-Routing protocols 2COMPUTER COMMUNICATION NETWORKS-R-Routing protocols 2
COMPUTER COMMUNICATION NETWORKS-R-Routing protocols 2
 
Computer Communication Networks-Routing protocols 1
Computer Communication Networks-Routing protocols 1Computer Communication Networks-Routing protocols 1
Computer Communication Networks-Routing protocols 1
 
Computer Communication Networks-Wireless LAN
Computer Communication Networks-Wireless LANComputer Communication Networks-Wireless LAN
Computer Communication Networks-Wireless LAN
 
Computer Communication Networks-Network Layer
Computer Communication Networks-Network LayerComputer Communication Networks-Network Layer
Computer Communication Networks-Network Layer
 
Lk module3
Lk module3Lk module3
Lk module3
 
Lk module4 structures
Lk module4 structuresLk module4 structures
Lk module4 structures
 
Lk module5 pointers
Lk module5 pointersLk module5 pointers
Lk module5 pointers
 

Recently uploaded

How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...RKavithamani
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
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
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxRoyAbrique
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 

Recently uploaded (20)

How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.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
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
Staff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSDStaff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSD
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 

Lk module4 file

  • 1. [Type the document title] Compiled & Edited by: Prof. L. Krishnananda, HOD, Dept of ECE, GSKSJTI, Bengaluru Page 1 File Operations in C:  In C, we use a FILE * data type to access files.  FILE * is defined in /usr/include/stdio.h An example: #include <stdio.h> int main( ) { FILE *fp; // create a pointer of type FILE fp = fopen("tmp.txt", "w"); fprintf (fp,"This is a testn"); fclose(fp); return 0; } 4.6.1 Opening a File: You must include <stdio.h> Prototype Form: FILE * fopen (const char * filename, const char * mode) FILE is a structure type declared in stdio.h. – No need to know the details of the structure. – fopen returns a pointer to the FILE structure type. – You must declare a pointer of type FILE to receive that value when it is returned. – Use the returned pointer in all subsequent references to that file. – If fopen fails, NULL is returned. The argument filename is the name of the file to be opened. Values of mode: Enclose in double quotes or pass as a string variable Modes: r: open the file for reading (NULL if it doesn’t exist) w: create for writing. destroy old if file exists a: open for writing. create if not there. start at the end-of-file r+: open for update (r/w). create if not there. start at the beginning. w+: create for r/w. destroy old if there a+: open for r/w. create if not there. start at the end-of-file In the text book, there are other binary modes with the letter b. They have no effect in today’s C compilers. 4.6.2 Stdin, stdout, stderr:  Every C program has three files opened for them at start-up: stdin, stdout, and stderr  stdin is opened for reading, while stdout and stderr are opened for writing  They can be used wherever a FILE * can be used. Examples: – fprintf (stdout, "Hello there!n"); This is the same as printf("Hello there!n"); – fscanf (stdin, "%d", &int_var); This is the same as scanf("%d", &int_var); – fprintf (stderr, "An error has occurred!n"); This is useful to report errors to standard error - it flushes output as well, so this is really good for debugging!
  • 2. [Type the document title] Compiled & Edited by: Prof. L. Krishnananda, HOD, Dept of ECE, GSKSJTI, Bengaluru Page 2 4.6.3 The exit ( ) function: This is used to leave the program at anytime from anywhere before the “normal” exit location. Syntax: exit (status); Example: #include <stdlib.h> …… if( (fp=fopen("a.txt","r")) == NULL) { fprintf(stderr, "Cannot open file a.txt!n"); exit (1); } Four ways to Read and Write Files:  Formatted file I/O  Get and put a character  Get and put a line  Block read and write 4.7.1 Formatted File I/O: Formatted File input is done through fscanf: – int fscanf (FILE * fp, const char * fmt, ...) ; Formatted File output is done through fprintf: – int fprintf(FILE *fp, const char *fmt, …); { FILE *fp1, *fp2; int n; fp1 = fopen ("file1", "r"); fp2 = fopen ("file2", "w"); fscanf (fp1, "%d", &n); fprint f(fp2, "%d", n); fclose (fp1); fclose (fp2); } 4.7.2 Get & Put a Character: #include <stdio.h> int fgetc (FILE * fp); int fputc (int c, FILE * fp); These two functions read or write a single byte from or to a file.  fgetc returns the character that was read, converted to an integer.  fputc returns the same value of parameter c if it succeeds, otherwise, return EOF. 4.7.3 Get & Put a Line: #include <stdio.h> char *fgets(char *s, int n, FILE * fp); int fputs (char *s, FILE * fp); These two functions read or write a string from or to a file.
  • 3. [Type the document title] Compiled & Edited by: Prof. L. Krishnananda, HOD, Dept of ECE, GSKSJTI, Bengaluru Page 3  gets reads an entire line into s, up to n-1 characters in length (pass the size of the character array s in as n to be safe!)  fgets returns the pointer s on success, or NULL if an error or end-of-file is reached.  fputs returns the number of characters written if successful; otherwise, return EOF. 4.7.4 fwrite and fread fread and fwrite are binary file reading and writing functions – Prototypes are found in stdio.h Generic Form: int fwrite (void *buf, int size, int count, FILE *fp) ; int fread (void *buf, int size, int count, FILE *fp) ; buf: is a pointer to the region in memory to be written/read – It can be a pointer to anything size: the size in bytes of each individual data item count: the number of data items to be written/read For example, a 100 element array of integers can be written as – fwrite( buf, sizeof(int), 100, fp); The fwrite (fread) returns the number of items actually written (read). Testing for errors: if ((frwrite (buf, size, count, fp)) != count) fprintf (stderr, "Error writing to file."); Writing a single double variable x to a file: fwrite (&x, sizeof(double), 1, fp) ; This writes the double x to the file in raw binary format. i.e., it simply writes the internal machine format of x Writing an array text[50] of 50 characters can be done by: – fwrite (text, sizeof (char), 50, fp) ; or – fwrite (text, sizeof(text), 1, fp); /* text must be a local array name */ Note: fread and frwrite are more efficient than fscanf and fprintf 4.7.5 Closing and Flushing Files: Syntax: int fclose (FILE * fp) ; closes fp -- returns 0 if it works -1 if it fails You can clear a buffer without closing it int fflush (FILE * fp) ; Essentially this is a force to disk. Very useful when debugging. Without fclose or fflush, your updates to a file may not be written to the file on disk. (Operating systems like Unix usually use “write caching” disk access.) 4.7.6 Detecting end of File: Text mode files: while ( (c = fgetc (fp) ) != EOF ) – Reads characters until it encounters the EOF – The problem is that the byte of data read may not be distinguishable from EOF.
  • 4. [Type the document title] Compiled & Edited by: Prof. L. Krishnananda, HOD, Dept of ECE, GSKSJTI, Bengaluru Page 4 Binary mode files: int feof (FILE * fp) ; – Note: the feof function realizes the end of file only after a reading failed (fread, fscanf, fgetc … ) fseek (fp,0,SEEK_END); printf ("%dn", feof(fp)); /* zero value */ fgetc (fp); /* fgetc returns -1 */ printf("%dn",feof(fp)); /* nonzero value */ Example: #define BUFSIZE 100 int main ( ) { char buf[BUFSIZE]; if ( (fp=fopen("file1", "r"))==NULL) { fprintf (stderr,"Error opening file."); exit (1); } while (!feof(fp)) { fgets (buf, BUFSIZE, fp); printf ("%s",buf); } // end of while fclose (fp); return 0; } // end of main
  • 5. [Type the document title] Compiled & Edited by: Prof. L. Krishnananda, HOD, Dept of ECE, GSKSJTI, Bengaluru Page 5 The fgets() function meets the possible overflow problem by taking as second argument that limits the number of characters to be read. This function is designed for file input, which makes it a little more awkward to use. Here is how fgets() differs from gets(): 1.It takes a second argument indicating the maximum number of characters to read. If this argument has the value n , fgets()reads up to n-1 characters or through the newline character, whichever comes first. 2.If fgets()reads the newline, it stores it in the string, unlike gets(), which discards it. 3.It takes a third argument indicating which file to read. To read from the keyboard, use stdin(for standard input ) as the argument; this identifier is defined in stdio.h. fputs() function: •It takes a string argument then prints it without adding a newline. #include <stdio.h> #define STLEN 14 int main(void) { char words[STLEN]; puts("Enter a string, please."); fgets(words, STLEN, stdin); printf("Your string twice (puts(), then fputs()):n"); puts(words); fputs(words, stdout); puts("Enter another string, please."); fgets(words, STLEN, stdin); printf("Your string twice (puts(), then fputs()):n"); puts(words); fputs(words, stdout);
  • 6. [Type the document title] Compiled & Edited by: Prof. L. Krishnananda, HOD, Dept of ECE, GSKSJTI, Bengaluru Page 6 puts("Done."); return0; } Output Enter a string, please. applegrapes Your string twice (puts(), thenfputs()): applegrapes applegrapes Enter another string,please. strawberryshortcake Your string twice (puts(),thenfputs()): strawberryshstrawberryshDone.