SlideShare a Scribd company logo
[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.
Ad

More Related Content

What's hot (18)

File in C language
File in C languageFile in C language
File in C language
Manash Kumar Mondal
 
Unit5 (2)
Unit5 (2)Unit5 (2)
Unit5 (2)
mrecedu
 
File Management in C
File Management in CFile Management in C
File Management in C
Paurav Shah
 
Unix systems programming interprocess communication/tutorialoutlet
Unix systems programming interprocess communication/tutorialoutletUnix systems programming interprocess communication/tutorialoutlet
Unix systems programming interprocess communication/tutorialoutlet
Beaglesz
 
File handling in C
File handling in CFile handling in C
File handling in C
Rabin 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 examples
Muhammed Thanveer M
 
File handling in c
File handling in cFile handling in c
File handling in c
mohit 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-dutt
Anil Dutt
 
C Programming Project
C Programming ProjectC Programming Project
C Programming Project
Vijayananda Mohire
 
Module 03 File Handling in C
Module 03 File Handling in CModule 03 File Handling in C
Module 03 File Handling in C
Tushar 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 C
Prabu U
 
Functions in python
Functions in pythonFunctions in python
Functions in python
Santosh Verma
 
File handling-c programming language
File handling-c programming languageFile handling-c programming language
File handling-c programming language
thirumalaikumar3
 
File handling in c
File  handling in cFile  handling in c
File handling in c
thirumalaikumar3
 
Bt0067 c programming and data structures2
Bt0067 c programming and data structures2Bt0067 c programming and data structures2
Bt0067 c programming and data structures2
Techglyphs
 
Programming in C
Programming in CProgramming in C
Programming in C
sujathavvv
 
Unit5 (2)
Unit5 (2)Unit5 (2)
Unit5 (2)
mrecedu
 
File Management in C
File Management in CFile Management in C
File Management in C
Paurav Shah
 
Unix systems programming interprocess communication/tutorialoutlet
Unix systems programming interprocess communication/tutorialoutletUnix systems programming interprocess communication/tutorialoutlet
Unix systems programming interprocess communication/tutorialoutlet
Beaglesz
 
File handling in C
File handling in CFile handling in C
File handling in C
Rabin 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 examples
Muhammed Thanveer M
 
File handling in c
File handling in cFile handling in c
File handling in c
mohit 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-dutt
Anil Dutt
 
Module 03 File Handling in C
Module 03 File Handling in CModule 03 File Handling in C
Module 03 File Handling in C
Tushar 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 C
Prabu U
 
File handling-c programming language
File handling-c programming languageFile handling-c programming language
File handling-c programming language
thirumalaikumar3
 
Bt0067 c programming and data structures2
Bt0067 c programming and data structures2Bt0067 c programming and data structures2
Bt0067 c programming and data structures2
Techglyphs
 
Programming in C
Programming in CProgramming in C
Programming in C
sujathavvv
 

Similar to Lk module4 file (20)

Handout#01
Handout#01Handout#01
Handout#01
Sunita Milind Dol
 
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
sangeeta borde
 
File handling-c
File handling-cFile handling-c
File handling-c
CGC Technical campus,Mohali
 
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
sudhakargeruganti
 
File management
File managementFile management
File management
lalithambiga kamaraj
 
want to learn files,then just use this ppt to learn
want to learn files,then just use this ppt to learnwant to learn files,then just use this ppt to learn
want to learn files,then just use this ppt to learn
nalluribalaji157
 
file handling1
file handling1file handling1
file handling1
student
 
Unit5
Unit5Unit5
Unit5
mrecedu
 
Unit5 C
Unit5 C Unit5 C
Unit5 C
arnold 7490
 
Module 5 file cp
Module 5 file cpModule 5 file cp
Module 5 file cp
Amarjith C K
 
File handling in c
File handling in cFile handling in c
File handling in c
aakanksha s
 
C Programming Unit-5
C Programming Unit-5C Programming Unit-5
C Programming Unit-5
Vikram Nandini
 
File Handling in c.ppt
File Handling in c.pptFile Handling in c.ppt
File Handling in c.ppt
BhumaNagaPavan
 
file_handling_in_c.ppt
file_handling_in_c.pptfile_handling_in_c.ppt
file_handling_in_c.ppt
DHARUNESHBOOPATHY
 
File handling in c Programming - Unit 5.1
File handling in c Programming - Unit 5.1File handling in c Programming - Unit 5.1
File handling in c Programming - Unit 5.1
Priyadarshini803769
 
Files_in_C.ppt
Files_in_C.pptFiles_in_C.ppt
Files_in_C.ppt
kasthurimukila
 
Programming C- File Handling , File Operation
Programming C- File Handling , File OperationProgramming C- File Handling , File Operation
Programming C- File Handling , File Operation
svkarthik86
 
file_handling_in_c.ppt
file_handling_in_c.pptfile_handling_in_c.ppt
file_handling_in_c.ppt
yuvrajkeshri
 
pre processor and file handling in c language ppt
pre processor and file handling in c language pptpre processor and file handling in c language ppt
pre processor and file handling in c language ppt
shreyasreddy703
 
C programming session 08
C programming session 08C programming session 08
C programming session 08
Dushmanta Nath
 
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
sangeeta borde
 
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
sudhakargeruganti
 
want to learn files,then just use this ppt to learn
want to learn files,then just use this ppt to learnwant to learn files,then just use this ppt to learn
want to learn files,then just use this ppt to learn
nalluribalaji157
 
file handling1
file handling1file handling1
file handling1
student
 
File handling in c
File handling in cFile handling in c
File handling in c
aakanksha s
 
File Handling in c.ppt
File Handling in c.pptFile Handling in c.ppt
File Handling in c.ppt
BhumaNagaPavan
 
File handling in c Programming - Unit 5.1
File handling in c Programming - Unit 5.1File handling in c Programming - Unit 5.1
File handling in c Programming - Unit 5.1
Priyadarshini803769
 
Programming C- File Handling , File Operation
Programming C- File Handling , File OperationProgramming C- File Handling , File Operation
Programming C- File Handling , File Operation
svkarthik86
 
file_handling_in_c.ppt
file_handling_in_c.pptfile_handling_in_c.ppt
file_handling_in_c.ppt
yuvrajkeshri
 
pre processor and file handling in c language ppt
pre processor and file handling in c language pptpre processor and file handling in c language ppt
pre processor and file handling in c language ppt
shreyasreddy703
 
C programming session 08
C programming session 08C programming session 08
C programming session 08
Dushmanta Nath
 
Ad

More from Krishna Nanda (16)

Python regular expressions
Python regular expressionsPython regular expressions
Python regular expressions
Krishna Nanda
 
Python dictionaries
Python dictionariesPython dictionaries
Python dictionaries
Krishna Nanda
 
Python lists
Python listsPython lists
Python lists
Krishna Nanda
 
Python-Tuples
Python-TuplesPython-Tuples
Python-Tuples
Krishna Nanda
 
Python- strings
Python- stringsPython- strings
Python- strings
Krishna Nanda
 
Python-files
Python-filesPython-files
Python-files
Krishna 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 layer
Krishna Nanda
 
Computer Communication Networks- TRANSPORT LAYER PROTOCOLS
Computer Communication Networks- TRANSPORT LAYER PROTOCOLSComputer Communication Networks- TRANSPORT LAYER PROTOCOLS
Computer Communication Networks- TRANSPORT LAYER PROTOCOLS
Krishna Nanda
 
COMPUTER COMMUNICATION NETWORKS -IPv4
COMPUTER COMMUNICATION NETWORKS -IPv4COMPUTER COMMUNICATION NETWORKS -IPv4
COMPUTER COMMUNICATION NETWORKS -IPv4
Krishna 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 2
Krishna Nanda
 
Computer Communication Networks-Routing protocols 1
Computer Communication Networks-Routing protocols 1Computer Communication Networks-Routing protocols 1
Computer Communication Networks-Routing protocols 1
Krishna Nanda
 
Computer Communication Networks-Wireless LAN
Computer Communication Networks-Wireless LANComputer Communication Networks-Wireless LAN
Computer Communication Networks-Wireless LAN
Krishna Nanda
 
Computer Communication Networks-Network Layer
Computer Communication Networks-Network LayerComputer Communication Networks-Network Layer
Computer Communication Networks-Network Layer
Krishna Nanda
 
Lk module3
Lk module3Lk module3
Lk module3
Krishna Nanda
 
Lk module4 structures
Lk module4 structuresLk module4 structures
Lk module4 structures
Krishna Nanda
 
Lk module5 pointers
Lk module5 pointersLk module5 pointers
Lk module5 pointers
Krishna Nanda
 
Python regular expressions
Python regular expressionsPython regular expressions
Python regular expressions
Krishna 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 layer
Krishna Nanda
 
Computer Communication Networks- TRANSPORT LAYER PROTOCOLS
Computer Communication Networks- TRANSPORT LAYER PROTOCOLSComputer Communication Networks- TRANSPORT LAYER PROTOCOLS
Computer Communication Networks- TRANSPORT LAYER PROTOCOLS
Krishna Nanda
 
COMPUTER COMMUNICATION NETWORKS -IPv4
COMPUTER COMMUNICATION NETWORKS -IPv4COMPUTER COMMUNICATION NETWORKS -IPv4
COMPUTER COMMUNICATION NETWORKS -IPv4
Krishna 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 2
Krishna Nanda
 
Computer Communication Networks-Routing protocols 1
Computer Communication Networks-Routing protocols 1Computer Communication Networks-Routing protocols 1
Computer Communication Networks-Routing protocols 1
Krishna Nanda
 
Computer Communication Networks-Wireless LAN
Computer Communication Networks-Wireless LANComputer Communication Networks-Wireless LAN
Computer Communication Networks-Wireless LAN
Krishna Nanda
 
Computer Communication Networks-Network Layer
Computer Communication Networks-Network LayerComputer Communication Networks-Network Layer
Computer Communication Networks-Network Layer
Krishna Nanda
 
Lk module4 structures
Lk module4 structuresLk module4 structures
Lk module4 structures
Krishna Nanda
 
Ad

Recently uploaded (20)

Mental Health Assessment in 5th semester bsc. nursing and also used in 2nd ye...
Mental Health Assessment in 5th semester bsc. nursing and also used in 2nd ye...Mental Health Assessment in 5th semester bsc. nursing and also used in 2nd ye...
Mental Health Assessment in 5th semester bsc. nursing and also used in 2nd ye...
parmarjuli1412
 
LDMMIA Reiki News Ed3 Vol1 For Team and Guests
LDMMIA Reiki News Ed3 Vol1 For Team and GuestsLDMMIA Reiki News Ed3 Vol1 For Team and Guests
LDMMIA Reiki News Ed3 Vol1 For Team and Guests
LDM Mia eStudios
 
Classification of mental disorder in 5th semester bsc. nursing and also used ...
Classification of mental disorder in 5th semester bsc. nursing and also used ...Classification of mental disorder in 5th semester bsc. nursing and also used ...
Classification of mental disorder in 5th semester bsc. nursing and also used ...
parmarjuli1412
 
ANTI-VIRAL DRUGS unit 3 Pharmacology 3.pptx
ANTI-VIRAL DRUGS unit 3 Pharmacology 3.pptxANTI-VIRAL DRUGS unit 3 Pharmacology 3.pptx
ANTI-VIRAL DRUGS unit 3 Pharmacology 3.pptx
Mayuri Chavan
 
2025 The Senior Landscape and SET plan preparations.pptx
2025 The Senior Landscape and SET plan preparations.pptx2025 The Senior Landscape and SET plan preparations.pptx
2025 The Senior Landscape and SET plan preparations.pptx
mansk2
 
antiquity of writing in ancient India- literary & archaeological evidence
antiquity of writing in ancient India- literary & archaeological evidenceantiquity of writing in ancient India- literary & archaeological evidence
antiquity of writing in ancient India- literary & archaeological evidence
PrachiSontakke5
 
LDMMIA Reiki Yoga S5 Daily Living Workshop
LDMMIA Reiki Yoga S5 Daily Living WorkshopLDMMIA Reiki Yoga S5 Daily Living Workshop
LDMMIA Reiki Yoga S5 Daily Living Workshop
LDM Mia eStudios
 
Overview Well-Being and Creative Careers
Overview Well-Being and Creative CareersOverview Well-Being and Creative Careers
Overview Well-Being and Creative Careers
University of Amsterdam
 
Chemotherapy of Malignancy -Anticancer.pptx
Chemotherapy of Malignancy -Anticancer.pptxChemotherapy of Malignancy -Anticancer.pptx
Chemotherapy of Malignancy -Anticancer.pptx
Mayuri Chavan
 
Search Matching Applicants in Odoo 18 - Odoo Slides
Search Matching Applicants in Odoo 18 - Odoo SlidesSearch Matching Applicants in Odoo 18 - Odoo Slides
Search Matching Applicants in Odoo 18 - Odoo Slides
Celine George
 
Pope Leo XIV, the first Pope from North America.pptx
Pope Leo XIV, the first Pope from North America.pptxPope Leo XIV, the first Pope from North America.pptx
Pope Leo XIV, the first Pope from North America.pptx
Martin M Flynn
 
Redesigning Education as a Cognitive Ecosystem: Practical Insights into Emerg...
Redesigning Education as a Cognitive Ecosystem: Practical Insights into Emerg...Redesigning Education as a Cognitive Ecosystem: Practical Insights into Emerg...
Redesigning Education as a Cognitive Ecosystem: Practical Insights into Emerg...
Leonel Morgado
 
How to Manage Amounts in Local Currency in Odoo 18 Purchase
How to Manage Amounts in Local Currency in Odoo 18 PurchaseHow to Manage Amounts in Local Currency in Odoo 18 Purchase
How to Manage Amounts in Local Currency in Odoo 18 Purchase
Celine George
 
Rock Art As a Source of Ancient Indian History
Rock Art As a Source of Ancient Indian HistoryRock Art As a Source of Ancient Indian History
Rock Art As a Source of Ancient Indian History
Virag Sontakke
 
How to Configure Public Holidays & Mandatory Days in Odoo 18
How to Configure Public Holidays & Mandatory Days in Odoo 18How to Configure Public Holidays & Mandatory Days in Odoo 18
How to Configure Public Holidays & Mandatory Days in Odoo 18
Celine George
 
Transform tomorrow: Master benefits analysis with Gen AI today webinar, 30 A...
Transform tomorrow: Master benefits analysis with Gen AI today webinar,  30 A...Transform tomorrow: Master benefits analysis with Gen AI today webinar,  30 A...
Transform tomorrow: Master benefits analysis with Gen AI today webinar, 30 A...
Association for Project Management
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...
BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...
BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...
Nguyen Thanh Tu Collection
 
How to Share Accounts Between Companies in Odoo 18
How to Share Accounts Between Companies in Odoo 18How to Share Accounts Between Companies in Odoo 18
How to Share Accounts Between Companies in Odoo 18
Celine George
 
E-Filing_of_Income_Tax.pptx and concept of form 26AS
E-Filing_of_Income_Tax.pptx and concept of form 26ASE-Filing_of_Income_Tax.pptx and concept of form 26AS
E-Filing_of_Income_Tax.pptx and concept of form 26AS
Abinash Palangdar
 
History Of The Monastery Of Mor Gabriel Philoxenos Yuhanon Dolabani
History Of The Monastery Of Mor Gabriel Philoxenos Yuhanon DolabaniHistory Of The Monastery Of Mor Gabriel Philoxenos Yuhanon Dolabani
History Of The Monastery Of Mor Gabriel Philoxenos Yuhanon Dolabani
fruinkamel7m
 
Mental Health Assessment in 5th semester bsc. nursing and also used in 2nd ye...
Mental Health Assessment in 5th semester bsc. nursing and also used in 2nd ye...Mental Health Assessment in 5th semester bsc. nursing and also used in 2nd ye...
Mental Health Assessment in 5th semester bsc. nursing and also used in 2nd ye...
parmarjuli1412
 
LDMMIA Reiki News Ed3 Vol1 For Team and Guests
LDMMIA Reiki News Ed3 Vol1 For Team and GuestsLDMMIA Reiki News Ed3 Vol1 For Team and Guests
LDMMIA Reiki News Ed3 Vol1 For Team and Guests
LDM Mia eStudios
 
Classification of mental disorder in 5th semester bsc. nursing and also used ...
Classification of mental disorder in 5th semester bsc. nursing and also used ...Classification of mental disorder in 5th semester bsc. nursing and also used ...
Classification of mental disorder in 5th semester bsc. nursing and also used ...
parmarjuli1412
 
ANTI-VIRAL DRUGS unit 3 Pharmacology 3.pptx
ANTI-VIRAL DRUGS unit 3 Pharmacology 3.pptxANTI-VIRAL DRUGS unit 3 Pharmacology 3.pptx
ANTI-VIRAL DRUGS unit 3 Pharmacology 3.pptx
Mayuri Chavan
 
2025 The Senior Landscape and SET plan preparations.pptx
2025 The Senior Landscape and SET plan preparations.pptx2025 The Senior Landscape and SET plan preparations.pptx
2025 The Senior Landscape and SET plan preparations.pptx
mansk2
 
antiquity of writing in ancient India- literary & archaeological evidence
antiquity of writing in ancient India- literary & archaeological evidenceantiquity of writing in ancient India- literary & archaeological evidence
antiquity of writing in ancient India- literary & archaeological evidence
PrachiSontakke5
 
LDMMIA Reiki Yoga S5 Daily Living Workshop
LDMMIA Reiki Yoga S5 Daily Living WorkshopLDMMIA Reiki Yoga S5 Daily Living Workshop
LDMMIA Reiki Yoga S5 Daily Living Workshop
LDM Mia eStudios
 
Overview Well-Being and Creative Careers
Overview Well-Being and Creative CareersOverview Well-Being and Creative Careers
Overview Well-Being and Creative Careers
University of Amsterdam
 
Chemotherapy of Malignancy -Anticancer.pptx
Chemotherapy of Malignancy -Anticancer.pptxChemotherapy of Malignancy -Anticancer.pptx
Chemotherapy of Malignancy -Anticancer.pptx
Mayuri Chavan
 
Search Matching Applicants in Odoo 18 - Odoo Slides
Search Matching Applicants in Odoo 18 - Odoo SlidesSearch Matching Applicants in Odoo 18 - Odoo Slides
Search Matching Applicants in Odoo 18 - Odoo Slides
Celine George
 
Pope Leo XIV, the first Pope from North America.pptx
Pope Leo XIV, the first Pope from North America.pptxPope Leo XIV, the first Pope from North America.pptx
Pope Leo XIV, the first Pope from North America.pptx
Martin M Flynn
 
Redesigning Education as a Cognitive Ecosystem: Practical Insights into Emerg...
Redesigning Education as a Cognitive Ecosystem: Practical Insights into Emerg...Redesigning Education as a Cognitive Ecosystem: Practical Insights into Emerg...
Redesigning Education as a Cognitive Ecosystem: Practical Insights into Emerg...
Leonel Morgado
 
How to Manage Amounts in Local Currency in Odoo 18 Purchase
How to Manage Amounts in Local Currency in Odoo 18 PurchaseHow to Manage Amounts in Local Currency in Odoo 18 Purchase
How to Manage Amounts in Local Currency in Odoo 18 Purchase
Celine George
 
Rock Art As a Source of Ancient Indian History
Rock Art As a Source of Ancient Indian HistoryRock Art As a Source of Ancient Indian History
Rock Art As a Source of Ancient Indian History
Virag Sontakke
 
How to Configure Public Holidays & Mandatory Days in Odoo 18
How to Configure Public Holidays & Mandatory Days in Odoo 18How to Configure Public Holidays & Mandatory Days in Odoo 18
How to Configure Public Holidays & Mandatory Days in Odoo 18
Celine George
 
Transform tomorrow: Master benefits analysis with Gen AI today webinar, 30 A...
Transform tomorrow: Master benefits analysis with Gen AI today webinar,  30 A...Transform tomorrow: Master benefits analysis with Gen AI today webinar,  30 A...
Transform tomorrow: Master benefits analysis with Gen AI today webinar, 30 A...
Association for Project Management
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...
BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...
BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...
Nguyen Thanh Tu Collection
 
How to Share Accounts Between Companies in Odoo 18
How to Share Accounts Between Companies in Odoo 18How to Share Accounts Between Companies in Odoo 18
How to Share Accounts Between Companies in Odoo 18
Celine George
 
E-Filing_of_Income_Tax.pptx and concept of form 26AS
E-Filing_of_Income_Tax.pptx and concept of form 26ASE-Filing_of_Income_Tax.pptx and concept of form 26AS
E-Filing_of_Income_Tax.pptx and concept of form 26AS
Abinash Palangdar
 
History Of The Monastery Of Mor Gabriel Philoxenos Yuhanon Dolabani
History Of The Monastery Of Mor Gabriel Philoxenos Yuhanon DolabaniHistory Of The Monastery Of Mor Gabriel Philoxenos Yuhanon Dolabani
History Of The Monastery Of Mor Gabriel Philoxenos Yuhanon Dolabani
fruinkamel7m
 

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.
  翻译: