SlideShare une entreprise Scribd logo
1  sur  48
Files
Programming for
Problem Solving using C
Mr. R. Prathap Kumar
Department of Computer Science
Engineering
Files
Syllabus
FILES: Introduction to files, Streams, I/O
using streams – opening a stream, closing
stream; Character input, Character output,
File position indicator, End of file and errors,
Line input and line output, Formatted I/O,
Block input and output, File type, Files and
command line arguments.
Files
Files:
 A file is an external collection of related data
treated as a unit.
 The aim of a file is to keep a record of data.
 Since the contents of primary memory lost
when the computer is shut down, we need
files to store data in a more permanent form.
 Additionally, the collection of data is often
too large to reside entirely in main memory
at one time.
Files
 Files are stored in auxiliary or secondary
storage devices.
 The two most common forms of secondary
storage are disk (hard disk, CD, and DVD)
and tape.
 The stdio.h header file defines the file
structure;
 FILE is predefined datatype. When we need
a file in our program, we declare it using the
FILE type.
 FILE *sp; //sp is a pointer to type FILE
Files
Streams
 Stream is a buffer. It will act as interface between
terminals (such as keyboard,monitor etc..)
 It receives or send data as sequence of byes
 There are two types of streams
1. input stream
2. output stream
 Input stream will send the data to the program by taking
from keyboard or file
 Output Stream will send the data to the monitor or file
by taking from the program
Files
Files
Text files vs Binary files:
In text files, everything is stored in terms of text
i.e. even if we store an integer 54; it will be
stored as a 2- bytes. In a text file certain
character translation may occur.
A binary file Contains data that was written in
the same format used to store internally in main
memory. For example, the integer value 1245
will be stored in 2 bytes depending on the
machine while it will require 4 bytes in a text
file.
Files
Text File Binary File
Bits represent character. Bits represent a custom data.
Less prone to get corrupt as
changes reflect as soon as the
file is opened and can easily be
undone.
Can easily get corrupted, even a
single bit change may corrupt
the file.
Can store only plain text in a
file.
Can store different types of data
(image, audio, text) in a single
file.
Mostly .txt , .dat, .c and .rtf are
used as extensions to text files.
Can have any application
defined extension .jpg,.png,.exe.
Files
Files
I/O Using streams
Files
Files
File Handling Functions
Files
Files
Files
File opening modes
Files
Files
Files
Closing file:
Files
Character Input/Output Functions
getc()/fgetc()
Character input functions read one character at a
time from a file.
putc()/fputc()
Character output functions write one character
at the time to a file
Files
Write a C program to read and write a character
from/into a file
#include<stdio.h>
main(){
FILE *fp;
char ch;
fp = fopen("one.txt", "w");
printf("Enter data...");
ch=getchar();
putc(ch, fp);
fclose(fp);
Files
fp = fopen("one.txt", "r");
printf(“nThe data in the file is”);
ch=getc(fp);
printf("%c",ch);
fclose(fp);
}
Files
Write a C program to read and write text
from/into a file
#include<stdio.h>
main(){
FILE *fp;
char ch;
fp = fopen("one.txt", "w");
printf("Enter data...");
while( (ch=getchar())!=EOF) {
putc(ch, fp); }
fclose(fp);
Files
fp = fopen("one.txt", "r");
printf(“nThe data in the file is”);
while((ch=getc(fp))!=EOF)
printf("%c",ch);
fclose(fp);
}
Files
Write a program in C to copy a file in another
name.
#include<stdio.h>
main(){
FILE *fp1,*fp2;
char ch;
fp1 = fopen("one.txt", "w");
printf("Enter data...");
while((ch=getchar())!=EOF) {
fputc(ch, fp1); }
fclose(fp1);
Files
fp1 = fopen("one.txt", "r");
fp2 = fopen("two.txt", "w");
while((ch=fgetc(fp1))!=EOF){
fputc(ch, fp2);
printf("%c",ch);
}
printf("file coied successfully");
fclose(fp1);
fclose(fp2);
}
Files
Line Input/Output Functions
fgets()
It read one line at a time from a file.
fputs()
It write one line at the time to a file
Files
Writing File : fputs() function
Syntax:
int fputs(const char *s, FILE *stream)
Reading File : fgets() function
Syntax:
char* fgets(char *s, int n, FILE *stream)
Files
//WAP to write and read string into/from file
#include<stdio.h>
void main(){
FILE *fp;
char text[300];
fp=fopen("myfile2.txt","w");
fputs("hello c programming",fp);
fclose(fp);
fp=fopen("myfile2.txt","r");
fgets(text,200,fp);
printf("%s",text);
fclose(fp);
} Output:
hello c programming
Files
Formatting Input/Output functions:
fscanf() and fprintf()
If the file contains data in the form of digits,
real numbers, characters and strings, then
character input/output functions are not enough
as the values would be read in the form of
characters.
The syntax for these functions is:
int fscanf(FILE *fp, char *format,. . .);
int fprintf(FILE *fp, char *format,. . .);
Files
/* Write a program in C to copy a file in another
name. */
#include<stdio.h>
#include<stdlib.h>
int main() {
FILE *fp1,*fp2;
int a,b;
fp1=fopen("one.txt", "w");
printf("Enter a and b values from key board: n");
scanf("%d%d",&a,&b); /* read from keyboard */
fprintf(fp1, "%d %d",a,b); /* write to file */
fclose(fp1);
Files
fp1=fopen("one.txt","r");
fp2=fopen("two.txt","w");
fscanf(fp1,"%d%d",&a, &b); /* read from file */
fprintf(fp2,"A t B n");
fprintf(fp2,"%d t %d",a,b);
printf("copied successfully");
fclose(fp1);
fclose(fp2);
}
Files
File Positioning / Random-Access I/O
functions
fseek()
ftell()
rewind()
Files
fseek() function is used to move the file position
to a desired location within the file.
Syntax:
int fseek(FILE *fp, long int numbytes, int
origin);
Here, fp is a file pointer returned by a call to
fopen( ),
numbytes is the number of bytes that pointer
moves from origin, which will become the new
current position.
Files
Origin is one of the following macros:
Origin Macro Name value
Beginning of file SEEK_SET 0
Current position SEEK_CUR 1
End of file SEEK_END 2
Files
Statement Meaning
fseek(fp,00,0) Go to the beginning.
fseek(fp,00,1) Stay at current position.
fseek(fp,-l,2) Go to the end of the file,
past the last character of the file.
fseek(fp,m,0) move to (m+1)th byte in
the file.
fseek(fp,m,1) Go Forward by m bytes.
fseek(fp,-m,1) Go Backward by m bytes
from the current position.
fseek(fp,-m,2) Go Backward by m
bytes from the end.
Files
ftell():
ftell() returns the location of the current position
of the file associated with fp.
If a failure occurs, it returns –1.
long int ftell(FILE *fp);
ftell takes a file pointer as argument and return a
number of type long that corresponds to the
current position.
Files
rewind( ):
The rewind( ) function moves the file position
indicator to the start of the specified file.
void rewind(FILE *fp);
 It also clears the end-of-file and error flags
associated with file.
 This function helps us reading the file more
than once, without having to close and open
the file.
Files
#include <stdio.h>
main(){
FILE *fp;
fp = fopen("myfile.txt","w+");
fputs("This is fseek , ftell, rewind demo
using fputs", fp);
fclose(fp);
fp = fopen("myfile.txt","r+");
printf("the cursor position %dn",ftell(fp));
printf("character=%c",fgetc(fp));
fseek( fp,6,SEEK_SET );
Files
printf("nthe cursor position %dn",ftell(fp));
printf("character=%c",fgetc(fp));
rewind(fp);
printf("nthe cursor position %dn",ftell(fp));
printf("character=%c",fgetc(fp));
fclose(fp); } output:
the cursor position 0
character=T
the cursor position 6
character=s
the cursor position 0
character=T
Files
Block Input/output functions:
fread( ) and fwrite( ):
To read and write data types that are longer than 1
byte, the C file system provides two functions:
fread( ) and fwrite( ).
These functions allow the reading and writing of
blocks of any type of data.
size_t fread (void *buffer, size_t num_bytes,
size_t count, FILE *fp);
size_t fwrite (const void *buffer, size_t
num_bytes, size_t count, FILE *fp);
Files
 For fread( ), buffer is a pointer to a region of
memory that will receive the data from the file.
 For fwrite( ), buffer is a pointer to the
information that will be written to the file.
 The value of count determines how many items
are read or written, with each item being num
bytes in length.
 fp is a file pointer to a previously opened stream.
Files
#include<stdio.h>
main(){
struct employee{
int eid;
char name[20];
char address[20];
};
FILE *fp;
struct employee emp;
fp=fopen("one.b","wb");
printf(" enter employee id,name and address n");
scanf("%d%s%s",&emp.eid,emp.name,emp.address);
Files
fwrite(&emp,sizeof(emp),1,fp);
fclose(fp);
printf(" display the employee details from
one.txt file n");
fp=fopen("one.b","rb");
fread(&emp,sizeof(emp),1,fp);
printf("Eid=%dnEname=%snAddress=%sn",e
mp.eid,emp.name,emp.address);
fclose(fp);
}
Files
Files and command line arguments.
It is a procedure of passing the arguments to the main function
from the command prompt.
/*This program reads a file specified by the user as a command
line argument and display the contents of the file on screen. */
#include <stdio.h>
int main(int argc, char *argv[]) {
FILE *fp; char *filename;
char ch;
Files
if (argc < 2) {
printf("Missing Filenamen"); return(1);
}
else {
filename = argv[1];
printf("Filename : %sn", filename);
}
fp = fopen(filename,"r");
Files
if ( fp!=NULL ) {
printf("File contents:n");
while ( (ch = fgetc(fp)) != EOF ) {
printf("%c",ch);
}
}
else {
printf("Failed to open the filen");
}
return(0);
}
Files
Hello.txt
Welcome to c programming
Output
$cc file1.c
$./a.out hello.txt
Welcome to c programming
Files

Contenu connexe

Similaire à PPS-II UNIT-5 PPT.pptx

Similaire à PPS-II UNIT-5 PPT.pptx (20)

C Programming Unit-5
C Programming Unit-5C Programming Unit-5
C Programming Unit-5
 
File handling-c
File handling-cFile handling-c
File handling-c
 
PPS PPT 2.pptx
PPS PPT 2.pptxPPS PPT 2.pptx
PPS PPT 2.pptx
 
INput output stream in ccP Full Detail.pptx
INput output stream in ccP Full Detail.pptxINput output stream in ccP Full Detail.pptx
INput output stream in ccP Full Detail.pptx
 
File management
File managementFile management
File management
 
file_handling_in_c.ppt
file_handling_in_c.pptfile_handling_in_c.ppt
file_handling_in_c.ppt
 
Unit 5 dwqb ans
Unit 5 dwqb ansUnit 5 dwqb ans
Unit 5 dwqb ans
 
Unit5 C
Unit5 C Unit5 C
Unit5 C
 
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 cFile handling in c
File handling in c
 
File handling
File handlingFile handling
File handling
 
VIT351 Software Development VI Unit5
VIT351 Software Development VI Unit5VIT351 Software Development VI Unit5
VIT351 Software Development VI Unit5
 
file handling1
file handling1file handling1
file handling1
 
file_c.pdf
file_c.pdffile_c.pdf
file_c.pdf
 
Unit5
Unit5Unit5
Unit5
 
file_handling_in_c.ppt
file_handling_in_c.pptfile_handling_in_c.ppt
file_handling_in_c.ppt
 
Chapter 13.1.10
Chapter 13.1.10Chapter 13.1.10
Chapter 13.1.10
 
File handling in C hhsjsjshsjjsjsjs.pptx
File handling in C hhsjsjshsjjsjsjs.pptxFile handling in C hhsjsjshsjjsjsjs.pptx
File handling in C hhsjsjshsjjsjsjs.pptx
 
Unit-VI.pptx
Unit-VI.pptxUnit-VI.pptx
Unit-VI.pptx
 
File in C language
File in C languageFile in C language
File in C language
 

Dernier

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
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfagholdier
 
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...Poonam Aher Patil
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptxMaritesTamaniVerdade
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfSherif Taha
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxVishalSingh1417
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.MaryamAhmad92
 
Third Battle of Panipat detailed notes.pptx
Third Battle of Panipat detailed notes.pptxThird Battle of Panipat detailed notes.pptx
Third Battle of Panipat detailed notes.pptxAmita Gupta
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxRamakrishna Reddy Bijjam
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docxPoojaSen20
 
Dyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptxDyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptxcallscotland1987
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docxPoojaSen20
 
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Ữ Â...Nguyen Thanh Tu Collection
 
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).pptxVishalSingh1417
 
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.pdfAdmir Softic
 
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...Association for Project Management
 
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.pdfPoh-Sun Goh
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxVishalSingh1417
 

Dernier (20)

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
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
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...
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdf
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
Third Battle of Panipat detailed notes.pptx
Third Battle of Panipat detailed notes.pptxThird Battle of Panipat detailed notes.pptx
Third Battle of Panipat detailed notes.pptx
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docx
 
Dyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptxDyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptx
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docx
 
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Ữ Â...
 
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
 
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
 
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
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptx
 

PPS-II UNIT-5 PPT.pptx

  • 1. Files Programming for Problem Solving using C Mr. R. Prathap Kumar Department of Computer Science Engineering
  • 2. Files Syllabus FILES: Introduction to files, Streams, I/O using streams – opening a stream, closing stream; Character input, Character output, File position indicator, End of file and errors, Line input and line output, Formatted I/O, Block input and output, File type, Files and command line arguments.
  • 3. Files Files:  A file is an external collection of related data treated as a unit.  The aim of a file is to keep a record of data.  Since the contents of primary memory lost when the computer is shut down, we need files to store data in a more permanent form.  Additionally, the collection of data is often too large to reside entirely in main memory at one time.
  • 4. Files  Files are stored in auxiliary or secondary storage devices.  The two most common forms of secondary storage are disk (hard disk, CD, and DVD) and tape.  The stdio.h header file defines the file structure;  FILE is predefined datatype. When we need a file in our program, we declare it using the FILE type.  FILE *sp; //sp is a pointer to type FILE
  • 5. Files Streams  Stream is a buffer. It will act as interface between terminals (such as keyboard,monitor etc..)  It receives or send data as sequence of byes  There are two types of streams 1. input stream 2. output stream  Input stream will send the data to the program by taking from keyboard or file  Output Stream will send the data to the monitor or file by taking from the program
  • 7. Files Text files vs Binary files: In text files, everything is stored in terms of text i.e. even if we store an integer 54; it will be stored as a 2- bytes. In a text file certain character translation may occur. A binary file Contains data that was written in the same format used to store internally in main memory. For example, the integer value 1245 will be stored in 2 bytes depending on the machine while it will require 4 bytes in a text file.
  • 8. Files Text File Binary File Bits represent character. Bits represent a custom data. Less prone to get corrupt as changes reflect as soon as the file is opened and can easily be undone. Can easily get corrupted, even a single bit change may corrupt the file. Can store only plain text in a file. Can store different types of data (image, audio, text) in a single file. Mostly .txt , .dat, .c and .rtf are used as extensions to text files. Can have any application defined extension .jpg,.png,.exe.
  • 11. Files
  • 13. Files
  • 14. Files
  • 16. Files
  • 17. Files
  • 19. Files Character Input/Output Functions getc()/fgetc() Character input functions read one character at a time from a file. putc()/fputc() Character output functions write one character at the time to a file
  • 20. Files Write a C program to read and write a character from/into a file #include<stdio.h> main(){ FILE *fp; char ch; fp = fopen("one.txt", "w"); printf("Enter data..."); ch=getchar(); putc(ch, fp); fclose(fp);
  • 21. Files fp = fopen("one.txt", "r"); printf(“nThe data in the file is”); ch=getc(fp); printf("%c",ch); fclose(fp); }
  • 22. Files Write a C program to read and write text from/into a file #include<stdio.h> main(){ FILE *fp; char ch; fp = fopen("one.txt", "w"); printf("Enter data..."); while( (ch=getchar())!=EOF) { putc(ch, fp); } fclose(fp);
  • 23. Files fp = fopen("one.txt", "r"); printf(“nThe data in the file is”); while((ch=getc(fp))!=EOF) printf("%c",ch); fclose(fp); }
  • 24. Files Write a program in C to copy a file in another name. #include<stdio.h> main(){ FILE *fp1,*fp2; char ch; fp1 = fopen("one.txt", "w"); printf("Enter data..."); while((ch=getchar())!=EOF) { fputc(ch, fp1); } fclose(fp1);
  • 25. Files fp1 = fopen("one.txt", "r"); fp2 = fopen("two.txt", "w"); while((ch=fgetc(fp1))!=EOF){ fputc(ch, fp2); printf("%c",ch); } printf("file coied successfully"); fclose(fp1); fclose(fp2); }
  • 26. Files Line Input/Output Functions fgets() It read one line at a time from a file. fputs() It write one line at the time to a file
  • 27. Files Writing File : fputs() function Syntax: int fputs(const char *s, FILE *stream) Reading File : fgets() function Syntax: char* fgets(char *s, int n, FILE *stream)
  • 28. Files //WAP to write and read string into/from file #include<stdio.h> void main(){ FILE *fp; char text[300]; fp=fopen("myfile2.txt","w"); fputs("hello c programming",fp); fclose(fp); fp=fopen("myfile2.txt","r"); fgets(text,200,fp); printf("%s",text); fclose(fp); } Output: hello c programming
  • 29. Files Formatting Input/Output functions: fscanf() and fprintf() If the file contains data in the form of digits, real numbers, characters and strings, then character input/output functions are not enough as the values would be read in the form of characters. The syntax for these functions is: int fscanf(FILE *fp, char *format,. . .); int fprintf(FILE *fp, char *format,. . .);
  • 30. Files /* Write a program in C to copy a file in another name. */ #include<stdio.h> #include<stdlib.h> int main() { FILE *fp1,*fp2; int a,b; fp1=fopen("one.txt", "w"); printf("Enter a and b values from key board: n"); scanf("%d%d",&a,&b); /* read from keyboard */ fprintf(fp1, "%d %d",a,b); /* write to file */ fclose(fp1);
  • 31. Files fp1=fopen("one.txt","r"); fp2=fopen("two.txt","w"); fscanf(fp1,"%d%d",&a, &b); /* read from file */ fprintf(fp2,"A t B n"); fprintf(fp2,"%d t %d",a,b); printf("copied successfully"); fclose(fp1); fclose(fp2); }
  • 32. Files File Positioning / Random-Access I/O functions fseek() ftell() rewind()
  • 33. Files fseek() function is used to move the file position to a desired location within the file. Syntax: int fseek(FILE *fp, long int numbytes, int origin); Here, fp is a file pointer returned by a call to fopen( ), numbytes is the number of bytes that pointer moves from origin, which will become the new current position.
  • 34. Files Origin is one of the following macros: Origin Macro Name value Beginning of file SEEK_SET 0 Current position SEEK_CUR 1 End of file SEEK_END 2
  • 35. Files Statement Meaning fseek(fp,00,0) Go to the beginning. fseek(fp,00,1) Stay at current position. fseek(fp,-l,2) Go to the end of the file, past the last character of the file. fseek(fp,m,0) move to (m+1)th byte in the file. fseek(fp,m,1) Go Forward by m bytes. fseek(fp,-m,1) Go Backward by m bytes from the current position. fseek(fp,-m,2) Go Backward by m bytes from the end.
  • 36. Files ftell(): ftell() returns the location of the current position of the file associated with fp. If a failure occurs, it returns –1. long int ftell(FILE *fp); ftell takes a file pointer as argument and return a number of type long that corresponds to the current position.
  • 37. Files rewind( ): The rewind( ) function moves the file position indicator to the start of the specified file. void rewind(FILE *fp);  It also clears the end-of-file and error flags associated with file.  This function helps us reading the file more than once, without having to close and open the file.
  • 38. Files #include <stdio.h> main(){ FILE *fp; fp = fopen("myfile.txt","w+"); fputs("This is fseek , ftell, rewind demo using fputs", fp); fclose(fp); fp = fopen("myfile.txt","r+"); printf("the cursor position %dn",ftell(fp)); printf("character=%c",fgetc(fp)); fseek( fp,6,SEEK_SET );
  • 39. Files printf("nthe cursor position %dn",ftell(fp)); printf("character=%c",fgetc(fp)); rewind(fp); printf("nthe cursor position %dn",ftell(fp)); printf("character=%c",fgetc(fp)); fclose(fp); } output: the cursor position 0 character=T the cursor position 6 character=s the cursor position 0 character=T
  • 40. Files Block Input/output functions: fread( ) and fwrite( ): To read and write data types that are longer than 1 byte, the C file system provides two functions: fread( ) and fwrite( ). These functions allow the reading and writing of blocks of any type of data. size_t fread (void *buffer, size_t num_bytes, size_t count, FILE *fp); size_t fwrite (const void *buffer, size_t num_bytes, size_t count, FILE *fp);
  • 41. Files  For fread( ), buffer is a pointer to a region of memory that will receive the data from the file.  For fwrite( ), buffer is a pointer to the information that will be written to the file.  The value of count determines how many items are read or written, with each item being num bytes in length.  fp is a file pointer to a previously opened stream.
  • 42. Files #include<stdio.h> main(){ struct employee{ int eid; char name[20]; char address[20]; }; FILE *fp; struct employee emp; fp=fopen("one.b","wb"); printf(" enter employee id,name and address n"); scanf("%d%s%s",&emp.eid,emp.name,emp.address);
  • 43. Files fwrite(&emp,sizeof(emp),1,fp); fclose(fp); printf(" display the employee details from one.txt file n"); fp=fopen("one.b","rb"); fread(&emp,sizeof(emp),1,fp); printf("Eid=%dnEname=%snAddress=%sn",e mp.eid,emp.name,emp.address); fclose(fp); }
  • 44. Files Files and command line arguments. It is a procedure of passing the arguments to the main function from the command prompt. /*This program reads a file specified by the user as a command line argument and display the contents of the file on screen. */ #include <stdio.h> int main(int argc, char *argv[]) { FILE *fp; char *filename; char ch;
  • 45. Files if (argc < 2) { printf("Missing Filenamen"); return(1); } else { filename = argv[1]; printf("Filename : %sn", filename); } fp = fopen(filename,"r");
  • 46. Files if ( fp!=NULL ) { printf("File contents:n"); while ( (ch = fgetc(fp)) != EOF ) { printf("%c",ch); } } else { printf("Failed to open the filen"); } return(0); }
  • 47. Files Hello.txt Welcome to c programming Output $cc file1.c $./a.out hello.txt Welcome to c programming
  • 48. Files