SlideShare a Scribd company logo
1 of 4
Download to read offline
Topics
Text File Manipulation
Opening
Closing
Writing
Reading
C – Text File
This class covers how C programmers can create, open, close text file for their data
storage.
A file represents a sequence of bytes, regardless of it being a text file or a binary file.
C programming language provides access on high level functions as well as low level
(OS level) calls to handle file on your storage devices. This chapter will take you
through the important calls for file management.
Opening Files
You can use the fopen( ) function to create a new file or to open an existing file. This
call will initialize an object of the type FILE, which contains all the information
necessary to control the stream. The prototype of this function call is as follows −
FILE *fopen( const char * filename, const char * mode );
Here, filename is a string literal, which you will use to name your file, and
access mode can have one of the following values −
Sr.No. Mode & Description
1
r
Opens an existing text file for reading purpose.
2
w
Opens a text file for writing. If it does not exist, then a new file is created. Here your program
will start writing content from the beginning of the file.
3
a
Opens a text file for writing in appending mode. If it does not exist, then a new file is created.
Here your program will start appending content in the existing file content.
4
r+
Opens a text file for both reading and writing.
5
w+
Opens a text file for both reading and writing. It first truncates the file to zero length if it exists,
otherwise creates a file if it does not exist.
6
a+
Opens a text file for both reading and writing. It creates the file if it does not exist. The reading
will start from the beginning but writing can only be appended.
Closing a File
To close a file, use the fclose( ) function. The prototype of this function is −
int fclose( FILE *fp );
The fclose(-) function returns zero on success, or EOF if there is an error in closing
the file. This function actually flushes any data still pending in the buffer to the file,
closes the file, and releases any memory used for the file. The EOF is a constant
defined in the header file stdio.h.
There are various functions provided by C standard library to read and write a file,
character by character, or in the form of a fixed length string.
Writing a File
Following is the simplest function to write individual characters to a stream −
int fputc( int c, FILE *fp );
The function fputc() writes the character value of the argument c to the output stream
referenced by fp. It returns the written character written on success otherwise EOF if
there is an error. You can use the following functions to write a null-terminated string
to a stream −
int fputs( const char *s, FILE *fp );
The function fputs() writes the string s to the output stream referenced by fp. It returns
a non-negative value on success, otherwise EOF is returned in case of any error. You
can use int fprintf(FILE *fp,const char *format, ...) function as well to write a string
into a file. Try the following example.
Make sure you have /tmp directory available. If it is not, then before proceeding, you
must create this directory on your machine.
#include <stdio.h>
main() {
FILE *fp;
fp = fopen("/tmp/test.txt", "w+");
fprintf(fp, "This is testing for fprintf...n");
fputs("This is testing for fputs...n", fp);
fclose(fp);
}
When the above code is compiled and executed, it creates a new file test.txt in /tmp
directory and writes two lines using two different functions. Let us read this file in the
next section.
Reading a File
Given below is the simplest function to read a single character from a file −
int fgetc( FILE * fp );
The fgetc() function reads a character from the input file referenced by fp. The return
value is the character read, or in case of any error, it returns EOF. The following
function allows to read a string from a stream −
char *fgets( char *buf, int n, FILE *fp );
The functions fgets() reads up to n-1 characters from the input stream referenced by
fp. It copies the read string into the buffer buf, appending a null character to terminate
the string.
If this function encounters a newline character 'n' or the end of the file EOF before
they have read the maximum number of characters, then it returns only the characters
read up to that point including the new line character. You can also use int
fscanf(FILE *fp, const char *format, ...) function to read strings from a file, but it
stops reading after encountering the first space character.
#include <stdio.h>
main() {
FILE *fp;
char buff[255];
fp = fopen("/tmp/test.txt", "r");
fscanf(fp, "%s", buff);
printf("1: %sn", buff );
fgets(buff, 255, (FILE*)fp);
printf("2: %sn", buff );
fgets(buff, 255, (FILE*)fp);
printf("3: %sn", buff );
fclose(fp);
}
When the above code is compiled and executed, it reads the file created in the
previous section and produces the following result −
1: This
2: is testing for fprintf...
3: This is testing for fputs...
Let's see a little more in detail about what happened here. First, fscanf() read
just This because after that, it encountered a space, second call is for fgets() which
reads the remaining line till it encountered end of line. Finally, the last
call fgets() reads the second line completely.

More Related Content

What's hot

file handling1
file handling1file handling1
file handling1student
 
Files let you store data on secondary storage such as a hard disk so that you...
Files let you store data on secondary storage such as a hard disk so that you...Files let you store data on secondary storage such as a hard disk so that you...
Files let you store data on secondary storage such as a hard disk so that you...Bern Jamie
 
File handling in c
File handling in cFile handling in c
File handling in cmohit biswal
 
Read write program
Read write programRead write program
Read write programAMI AMITO
 
Chapter 13.1.10
Chapter 13.1.10Chapter 13.1.10
Chapter 13.1.10patcha535
 
File Management in C
File Management in CFile Management in C
File Management in CPaurav Shah
 
Bt0067 c programming and data structures2
Bt0067 c programming and data structures2Bt0067 c programming and data structures2
Bt0067 c programming and data structures2Techglyphs
 
C UNIT-5 PREPARED BY M V BRAHMANANDA REDDY
C UNIT-5 PREPARED BY M V BRAHMANANDA REDDYC UNIT-5 PREPARED BY M V BRAHMANANDA REDDY
C UNIT-5 PREPARED BY M V BRAHMANANDA REDDYRajeshkumar Reddy
 
Files in C
Files in CFiles in C
Files in CPrabu U
 
Mesics lecture files in 'c'
Mesics lecture   files in 'c'Mesics lecture   files in 'c'
Mesics lecture files in 'c'eShikshak
 
C programming file handling
C  programming file handlingC  programming file handling
C programming file handlingargusacademy
 
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
 
source code which create file and write into it
source code which create file and write into itsource code which create file and write into it
source code which create file and write into itmelakusisay507
 

What's hot (20)

File in C language
File in C languageFile in C language
File in C language
 
file handling1
file handling1file handling1
file handling1
 
Files let you store data on secondary storage such as a hard disk so that you...
Files let you store data on secondary storage such as a hard disk so that you...Files let you store data on secondary storage such as a hard disk so that you...
Files let you store data on secondary storage such as a hard disk so that you...
 
File handling in c
File handling in cFile handling in c
File handling in c
 
Read write program
Read write programRead write program
Read write program
 
Satz1
Satz1Satz1
Satz1
 
File handling in c
File  handling in cFile  handling in c
File handling in c
 
Chapter 13.1.10
Chapter 13.1.10Chapter 13.1.10
Chapter 13.1.10
 
File Management in C
File Management in CFile Management in C
File Management in C
 
C Programming Unit-5
C Programming Unit-5C Programming Unit-5
C Programming Unit-5
 
Bt0067 c programming and data structures2
Bt0067 c programming and data structures2Bt0067 c programming and data structures2
Bt0067 c programming and data structures2
 
C UNIT-5 PREPARED BY M V BRAHMANANDA REDDY
C UNIT-5 PREPARED BY M V BRAHMANANDA REDDYC UNIT-5 PREPARED BY M V BRAHMANANDA REDDY
C UNIT-5 PREPARED BY M V BRAHMANANDA REDDY
 
Lk module4 file
Lk module4 fileLk module4 file
Lk module4 file
 
File Management
File ManagementFile Management
File Management
 
Files in C
Files in CFiles in C
Files in C
 
Mesics lecture files in 'c'
Mesics lecture   files in 'c'Mesics lecture   files in 'c'
Mesics lecture files in 'c'
 
C programming file handling
C  programming file handlingC  programming file handling
C programming file handling
 
Module 03 File Handling in C
Module 03 File Handling in CModule 03 File Handling in C
Module 03 File Handling in C
 
source code which create file and write into it
source code which create file and write into itsource code which create file and write into it
source code which create file and write into it
 
C language updated
C language updatedC language updated
C language updated
 

Similar to 4 text file

Similar to 4 text file (20)

Handout#01
Handout#01Handout#01
Handout#01
 
File handling in c
File handling in cFile handling in c
File handling 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.pdf
 
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.ppt
File Handling in c.pptFile Handling in c.ppt
File Handling in c.ppt
 
Module 5 file cp
Module 5 file cpModule 5 file cp
Module 5 file cp
 
UNIT 10. Files and file handling in C
UNIT 10. Files and file handling in CUNIT 10. Files and file handling in C
UNIT 10. Files and file handling in C
 
File management
File managementFile management
File management
 
Unit-VI.pptx
Unit-VI.pptxUnit-VI.pptx
Unit-VI.pptx
 
file handling, dynamic memory allocation
file handling, dynamic memory allocationfile handling, dynamic memory allocation
file handling, dynamic memory allocation
 
VIT351 Software Development VI Unit5
VIT351 Software Development VI Unit5VIT351 Software Development VI Unit5
VIT351 Software Development VI Unit5
 
Unit 8
Unit 8Unit 8
Unit 8
 
File in c
File in cFile in c
File in c
 
file_handling_in_c.ppt
file_handling_in_c.pptfile_handling_in_c.ppt
file_handling_in_c.ppt
 
PPS PPT 2.pptx
PPS PPT 2.pptxPPS PPT 2.pptx
PPS PPT 2.pptx
 
C programming session 08
C programming session 08C programming session 08
C programming session 08
 
File handling-c
File handling-cFile handling-c
File handling-c
 
Unit5 C
Unit5 C Unit5 C
Unit5 C
 
file_handling_in_c.ppt
file_handling_in_c.pptfile_handling_in_c.ppt
file_handling_in_c.ppt
 
FILES IN C
FILES IN CFILES IN C
FILES IN C
 

Recently uploaded

Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docxPoojaSen20
 
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
 
Micromeritics - Fundamental and Derived Properties of Powders
Micromeritics - Fundamental and Derived Properties of PowdersMicromeritics - Fundamental and Derived Properties of Powders
Micromeritics - Fundamental and Derived Properties of PowdersChitralekhaTherkar
 
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
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991RKavithamani
 
PSYCHIATRIC History collection FORMAT.pptx
PSYCHIATRIC   History collection FORMAT.pptxPSYCHIATRIC   History collection FORMAT.pptx
PSYCHIATRIC History collection FORMAT.pptxPoojaSen20
 
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
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 
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
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting DataJhengPantaleon
 
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
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAssociation for Project Management
 
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
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 

Recently uploaded (20)

Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docx
 
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
 
Micromeritics - Fundamental and Derived Properties of Powders
Micromeritics - Fundamental and Derived Properties of PowdersMicromeritics - Fundamental and Derived Properties of Powders
Micromeritics - Fundamental and Derived Properties of Powders
 
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
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
 
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
 
PSYCHIATRIC History collection FORMAT.pptx
PSYCHIATRIC   History collection FORMAT.pptxPSYCHIATRIC   History collection FORMAT.pptx
PSYCHIATRIC History collection FORMAT.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
 
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
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
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
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
 
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
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
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
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 

4 text file

  • 2. C – Text File This class covers how C programmers can create, open, close text file for their data storage. A file represents a sequence of bytes, regardless of it being a text file or a binary file. C programming language provides access on high level functions as well as low level (OS level) calls to handle file on your storage devices. This chapter will take you through the important calls for file management. Opening Files You can use the fopen( ) function to create a new file or to open an existing file. This call will initialize an object of the type FILE, which contains all the information necessary to control the stream. The prototype of this function call is as follows − FILE *fopen( const char * filename, const char * mode ); Here, filename is a string literal, which you will use to name your file, and access mode can have one of the following values − Sr.No. Mode & Description 1 r Opens an existing text file for reading purpose. 2 w Opens a text file for writing. If it does not exist, then a new file is created. Here your program will start writing content from the beginning of the file. 3 a Opens a text file for writing in appending mode. If it does not exist, then a new file is created. Here your program will start appending content in the existing file content. 4 r+ Opens a text file for both reading and writing. 5 w+ Opens a text file for both reading and writing. It first truncates the file to zero length if it exists, otherwise creates a file if it does not exist. 6 a+ Opens a text file for both reading and writing. It creates the file if it does not exist. The reading will start from the beginning but writing can only be appended.
  • 3. Closing a File To close a file, use the fclose( ) function. The prototype of this function is − int fclose( FILE *fp ); The fclose(-) function returns zero on success, or EOF if there is an error in closing the file. This function actually flushes any data still pending in the buffer to the file, closes the file, and releases any memory used for the file. The EOF is a constant defined in the header file stdio.h. There are various functions provided by C standard library to read and write a file, character by character, or in the form of a fixed length string. Writing a File Following is the simplest function to write individual characters to a stream − int fputc( int c, FILE *fp ); The function fputc() writes the character value of the argument c to the output stream referenced by fp. It returns the written character written on success otherwise EOF if there is an error. You can use the following functions to write a null-terminated string to a stream − int fputs( const char *s, FILE *fp ); The function fputs() writes the string s to the output stream referenced by fp. It returns a non-negative value on success, otherwise EOF is returned in case of any error. You can use int fprintf(FILE *fp,const char *format, ...) function as well to write a string into a file. Try the following example. Make sure you have /tmp directory available. If it is not, then before proceeding, you must create this directory on your machine. #include <stdio.h> main() { FILE *fp; fp = fopen("/tmp/test.txt", "w+"); fprintf(fp, "This is testing for fprintf...n"); fputs("This is testing for fputs...n", fp); fclose(fp); } When the above code is compiled and executed, it creates a new file test.txt in /tmp directory and writes two lines using two different functions. Let us read this file in the next section.
  • 4. Reading a File Given below is the simplest function to read a single character from a file − int fgetc( FILE * fp ); The fgetc() function reads a character from the input file referenced by fp. The return value is the character read, or in case of any error, it returns EOF. The following function allows to read a string from a stream − char *fgets( char *buf, int n, FILE *fp ); The functions fgets() reads up to n-1 characters from the input stream referenced by fp. It copies the read string into the buffer buf, appending a null character to terminate the string. If this function encounters a newline character 'n' or the end of the file EOF before they have read the maximum number of characters, then it returns only the characters read up to that point including the new line character. You can also use int fscanf(FILE *fp, const char *format, ...) function to read strings from a file, but it stops reading after encountering the first space character. #include <stdio.h> main() { FILE *fp; char buff[255]; fp = fopen("/tmp/test.txt", "r"); fscanf(fp, "%s", buff); printf("1: %sn", buff ); fgets(buff, 255, (FILE*)fp); printf("2: %sn", buff ); fgets(buff, 255, (FILE*)fp); printf("3: %sn", buff ); fclose(fp); } When the above code is compiled and executed, it reads the file created in the previous section and produces the following result − 1: This 2: is testing for fprintf... 3: This is testing for fputs... Let's see a little more in detail about what happened here. First, fscanf() read just This because after that, it encountered a space, second call is for fgets() which reads the remaining line till it encountered end of line. Finally, the last call fgets() reads the second line completely.