SlideShare une entreprise Scribd logo
1  sur  4
Télécharger pour lire hors ligne
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.

Contenu connexe

Tendances

file handling1
file handling1file handling1
file handling1
student
 
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
 
Read write program
Read write programRead write program
Read write program
AMI AMITO
 
Chapter 13.1.10
Chapter 13.1.10Chapter 13.1.10
Chapter 13.1.10
patcha535
 
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
Rajeshkumar Reddy
 

Tendances (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
 

Similaire à 4 text file

C programming session 08
C programming session 08C programming session 08
C programming session 08
Dushmanta Nath
 

Similaire à 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
 

Dernier

The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
heathfieldcps1
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
ZurliaSoop
 

Dernier (20)

Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxSKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
 
Interdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxInterdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptx
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentation
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptx
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
 
Spatium Project Simulation student brief
Spatium Project Simulation student briefSpatium Project Simulation student brief
Spatium Project Simulation student brief
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
 

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.