KEMBAR78
File handling in c Programming - Unit 5.1 | PPTX
Regards,
Mr.U.Udayakumar M.Sc., M.Phil., (Ph.D)
Assistant Professor
Department of Computer Science & Applications (B.Sc CS)
College of Science and Humanities
SRMIST, Ramapuram
File Handling in C
Mr.U.Udayakumar, Assistant Professor, Department of Computer Science
&
Applications(B.Sc CS), SRMIST, Ramapuram
1
Contents
⚫Files – Definition
⚫File types
⚫File Permission
⚫Writing and Reading Contents to File
⚫Difference between Append and
Write
⚫File Handling Functions
Mr.U.Udayakumar, Assistant Professor, Department of Computer Science
&
Applications(B.Sc CS), SRMIST, Ramapuram
2
Files
⚫ File handing in C is the process in which we create, open,
read, write, and close operations on a file.
⚫ C language provides different functions such as fopen(),
fwrite(), fread(), fseek(), fprintf(), etc. to perform input,
output, and many different C file operations in our
program.
Mr.U.Udayakumar, Assistant Professor, Department of Computer Science
&
Applications(B.Sc CS), SRMIST, Ramapuram
3
Why do we need File Handling in C?
⚫ Reusability: The data stored in the file can be accessed, updated,
and deleted anywhere and anytime providing high reusability.
⚫ Portability: Without losing any data, files can be transferred to
another in the computer system. The risk of flawed coding is
minimized with this feature.
⚫ Efficient: A large amount of input may be required for some
programs. File handling allows you to easily access a part of a file
using few instructions which saves a lot of time and reduces the
chance of errors.
⚫ Storage Capacity: Files allow you to store a large amount of data
without having to worry about storing everything simultaneously in a
prMor.gUr.Uadmaya.kumar, Assistant Professor, Department of
Computer Science &
4 Applications(B.Sc CS), SRMIST,
Ramapuram
Types of Files
 Text Files
 Binary Files
1. Text Files
 A text file contains data in the form of ASCII characters and is generally used to store a stream of characters.
 Each line in a text file ends with a new line character (‘n’).
 It can be read or written by any text editor.
 They are generally stored with .txt file extension.
 Text files can also be used to store the source code.
2. Binary Files
 A binary file contains data in binary form (i.e. 0’s and 1’s) instead of ASCII characters. They contain data that is
stored in a similar manner to how it is stored in the main memory.
 The binary files can be created only from within a program and their contents can only be read by a program.
 More secure as they are not easily readable.
 They are generally stored with .bin file extension.
Mr.U.Udayakumar, Assistant Professor, Department of Computer Science
&
Applications(B.Sc CS), SRMIST, Ramapuram
5
C File Operations
 Creating a new file – fopen() with attributes as “a” or “a+” or “w” or
“w+”
 Opening an existing file – fopen()
 Reading from file – fscanf() or fgets()
 Writing to a file – fprintf() or fputs()
 Moving to a specific location in a file – fseek(), rewind()
 Closing a file – fclose()
Mr.U.Udayakumar, Assistant Professor, Department of Computer Science
&
Applications(B.Sc CS), SRMIST, Ramapuram
6
Difference between append
and write
⚫File in the write mode, the file is reset, resulting in
deletion of any data already present in the file.
⚫While in append mode this will not happen. Append
mode is used to append or add data to the existing
data of file
Mr.U.Udayakumar, Assistant Professor, Department of Computer Science
&
Applications(B.Sc CS), SRMIST, Ramapuram
7
File Pointer in C
 A file pointer is a reference to a particular position in the opened file. It is used in file
handling to perform all file operations such as read, write, close, etc. We use the FILE
macro to declare the file pointer variable. The FILE macro is defined inside <stdio.h>
header file.
Syntax of File Pointer
FILE* pointer_name;
Open a File in C
For opening a file in C, the fopen() function is used with the filename or file path along
with the required access modes.
Syntax of fopen()
FILE* fopen(const char *file_name, const char *access_mode);
Parameters
⚫ file_name: name of the file when present in the same directory as the source
file.Otherwise, full path.
Mr.U.Udayakumar, Assistant Professor, Department of Computer Science
&
8 ⚫ acAceppslsic_amtioonsd(Be.:ScSCpSe)c, iSfRiMesISfTo,
rRawmhapautraomperation the file is being opened.
File opening modes in C
Mr.U.Udayakumar, Assistant Professor, Department of Computer Science
&
Applications(B.Sc CS), SRMIST, Ramapuram
9
Example – Create a new File
// C Program to create a file
#include <stdio.h>
#include <stdlib.h>
int main()
{
// file pointer
FILE* fptr;
// creating file using fopen() access mode "w"
fptr = fopen("file.txt", "w");
// checking if the file is created
if (fptr == NULL) {
printf("The file is
not opened. The
program will "
"exit
now"
);
exit(0);
}
else {
printf("The file is created Successfully.");
}
return 0;
Output
The file is created
Successfully.
Mr.U.Udayakumar, Assistant Professor, Department of Computer Science
&
Applications(B.Sc CS), SRMIST, Ramapuram
10 }
Reading From a File
ar);
⚫ The file read operation in C can be performed using functions fscanf() or
fgets(). Both the functions performed the same operations as that of scanf
and gets but with an additional parameter, the file pointer. There are also
other functions we can use to read from a file. Such functions are listed
below:
⚫ Example:
FILE * fptr;
fptr = fopen(“fileName.txt”, “r”);
fscanf(fptr, "%s %s %s %d", str1, str2, str3, &ye
char c = fgetc(fptr);
⚫ The getc() and some other file reading functions return EOF (End Of File)
when they reach the end of the file while reading. EOF indicates the end of
the file and its value is implementation-defined.
Mr.U.Udayakumar, Assistant Professor, Department of Computer Science
&
Applications(B.Sc CS), SRMIST, Ramapuram
11
Write data to a File
⚫ The file write operations can be performed by the functions fprintf()
and fputs() with similarities to read operations. C programming
also provides some other functions that can be used to write data
to a file such as:
⚫ Example:
FILE *fptr ;
fptr = fopen(“fileName.txt”, “w”);
fprintf(fptr, "%s %s %s %d", "We", "are", "in", 2012);
fputc("a", fptr);
Mr.U.Udayakumar, Assistant Professor, Department of Computer Science
&
Applications(B.Sc CS), SRMIST, Ramapuram
12
Program to copy from one file
to another file
13
void main()
{
FILE
*fp,*fp1; int
ch; clrscr();
fp=fopen("ex
_file4.c","r");
fp1=fopen("ex_file2.c","w");
if(fp==NULL)
printf(“File is not
available”); ch=getc(fp);
while(ch!=EOF)
{
putc(ch,fp1);
ch=getc(fp);
}
fclosMe(rf.pU).;Udayakumar,
Assistant Professor, Department
fscanf() and fprintf()
⚫ The functions fprintf() and fscanf() are similar to printf() and scanf() except that these functions
operate on files and require one additional and first argument to be a file pointer.
Example
#include <stdio.h>
main ()
{
FILE *fp;
float total;
fp =
fopen("da
ta.txt",
"w+");
if (fp ==
NULL) {
printf("data.txt does not exist, please check!n");
exit (1);
}
fprintf(fp, 100);
fscanf(fp, "%f", &total);
fclose(fp);
printf("Value of total is
Mr.U.Udayakumar, Assistant Professor, Department of Computer Science
&
Applications(B.Sc CS), SRMIST, Ramapuram
14
getc() and putc()
⚫The functions getc() and putc() are equivalent to
getchar() and putchar() functions
⚫Input and Output, except that these functions
require an argument which is the file
pointer.
⚫Function getc() reads a single character from the
file which has previously been opened using a
function
⚫getc(in_file);
⚫putc(c, out_file);
Mr.U.Udayakumar, Assistant Professor, Department of Computer Science
&
Applications(B.Sc CS), SRMIST, Ramapuram
15
Example
#include <stdio.h>
main ()
{
char in_file[30],
out_file[30];
FILE *fpin, *fpout;
int c;
printf("This program copies the source file to the
destination
file
nn");
printf("Enter name of the source file :");
scanf("%30s", in_file);
printf("Enter name of the destination file :");
scanf("%30s", out_file);
if((fpin=fopen(in_file, "r")) == NULL)
else if ((fpout=fopen(out_file, "w")) == NULL)
printf("Error could not open destination file for
readingn");
else
{
while((c =getc(fpin)) != EOF)
putc(c, fpout);
printf("Destination file has
been copiedn");
}
}
printf(M"rE.Urr.Uordacyoakuulmdanr,oAtssoisptaennt
Psroouferscseor,fiDleepfaortrment of Computer Science &
16 readinAgppnl"ic)a;tions(B.Sc CS), SRMIST, Ramapuram
ftell()
⚫ Functions ftell() and fseek() are important in a program
performing file manipulations. Function ftell() returns the
current position of the file pointer in a stream. The return
value is 0 or a positive integer indicating the byte offset
from the beginning of an open file.
long int ftell(FILE *fp);
Mr.U.Udayakumar, Assistant Professor, Department of Computer Science
&
Applications(B.Sc CS), SRMIST, Ramapuram
17
fseek()
⚫ This function positions the next I/O operation on an open stream
to a new position relative to the current position.
⚫ int fseek(FILE *fp, long int offset, int origin);
⚫ Here fp is the file pointer of the stream on which I/O operations
are carried on, offset is the number of bytes to skip over. The
offset can be either positive or negative, denting forward or
backward movement in the file. origin is the position in the
stream to which the offset is applied, this can be one of
thefollowing constants :
⚫ SEEK_SET : offset is relative to beginning of the file
⚫ SEEK_CUR : offset is relative to the current position in the file
⚫ SEEK_END : offset is relative to end of the file
Mr.U.Udayakumar, Assistant Professor, Department of Computer Science
&
Applications(B.Sc CS), SRMIST, Ramapuram
18
Example
#include <stdio.h>
#include <stdlib.h>
char buffer[11];
int
position;
main ()
{
FILE
*file_ptr; int
num;
if ((file_ptr =
fopen("test_fil
e", "w+f
10"))
Mr.U.Udayakumar, Assistant Professor, Department of Computer Science
&
Applications(B.Sc CS), SRMIST, Ramapuram
19
Example
printf("Error opening test_file 
n"); exit(1);
}
fputs("1111111111", file_ptr);
fputs("2222222222", file_ptr);
if ( (position = fseek(file_ptr,
10, SEEK_SET)) != 0)
{
printf("Error in seek
operation: errno n");
exit(1);
}
num = 11;
fgets(buffer, num, file_ptr);
printf("The record is %sn",
buffer); fclose(file_ptr);
}
Mr.U.Udayakumar, Assistant Professor, Department of Computer Science
&
Applications(B.Sc CS), SRMIST, Ramapuram
20
Thank you
21
Mr.U.Udayakumar, Assistant Professor, Department
of Computer Science & Applications(B.Sc CS),
SRMIST, Ramapuram

File handling in c Programming - Unit 5.1

  • 1.
    Regards, Mr.U.Udayakumar M.Sc., M.Phil.,(Ph.D) Assistant Professor Department of Computer Science & Applications (B.Sc CS) College of Science and Humanities SRMIST, Ramapuram File Handling in C Mr.U.Udayakumar, Assistant Professor, Department of Computer Science & Applications(B.Sc CS), SRMIST, Ramapuram 1
  • 2.
    Contents ⚫Files – Definition ⚫Filetypes ⚫File Permission ⚫Writing and Reading Contents to File ⚫Difference between Append and Write ⚫File Handling Functions Mr.U.Udayakumar, Assistant Professor, Department of Computer Science & Applications(B.Sc CS), SRMIST, Ramapuram 2
  • 3.
    Files ⚫ File handingin C is the process in which we create, open, read, write, and close operations on a file. ⚫ C language provides different functions such as fopen(), fwrite(), fread(), fseek(), fprintf(), etc. to perform input, output, and many different C file operations in our program. Mr.U.Udayakumar, Assistant Professor, Department of Computer Science & Applications(B.Sc CS), SRMIST, Ramapuram 3
  • 4.
    Why do weneed File Handling in C? ⚫ Reusability: The data stored in the file can be accessed, updated, and deleted anywhere and anytime providing high reusability. ⚫ Portability: Without losing any data, files can be transferred to another in the computer system. The risk of flawed coding is minimized with this feature. ⚫ Efficient: A large amount of input may be required for some programs. File handling allows you to easily access a part of a file using few instructions which saves a lot of time and reduces the chance of errors. ⚫ Storage Capacity: Files allow you to store a large amount of data without having to worry about storing everything simultaneously in a prMor.gUr.Uadmaya.kumar, Assistant Professor, Department of Computer Science & 4 Applications(B.Sc CS), SRMIST, Ramapuram
  • 5.
    Types of Files Text Files  Binary Files 1. Text Files  A text file contains data in the form of ASCII characters and is generally used to store a stream of characters.  Each line in a text file ends with a new line character (‘n’).  It can be read or written by any text editor.  They are generally stored with .txt file extension.  Text files can also be used to store the source code. 2. Binary Files  A binary file contains data in binary form (i.e. 0’s and 1’s) instead of ASCII characters. They contain data that is stored in a similar manner to how it is stored in the main memory.  The binary files can be created only from within a program and their contents can only be read by a program.  More secure as they are not easily readable.  They are generally stored with .bin file extension. Mr.U.Udayakumar, Assistant Professor, Department of Computer Science & Applications(B.Sc CS), SRMIST, Ramapuram 5
  • 6.
    C File Operations Creating a new file – fopen() with attributes as “a” or “a+” or “w” or “w+”  Opening an existing file – fopen()  Reading from file – fscanf() or fgets()  Writing to a file – fprintf() or fputs()  Moving to a specific location in a file – fseek(), rewind()  Closing a file – fclose() Mr.U.Udayakumar, Assistant Professor, Department of Computer Science & Applications(B.Sc CS), SRMIST, Ramapuram 6
  • 7.
    Difference between append andwrite ⚫File in the write mode, the file is reset, resulting in deletion of any data already present in the file. ⚫While in append mode this will not happen. Append mode is used to append or add data to the existing data of file Mr.U.Udayakumar, Assistant Professor, Department of Computer Science & Applications(B.Sc CS), SRMIST, Ramapuram 7
  • 8.
    File Pointer inC  A file pointer is a reference to a particular position in the opened file. It is used in file handling to perform all file operations such as read, write, close, etc. We use the FILE macro to declare the file pointer variable. The FILE macro is defined inside <stdio.h> header file. Syntax of File Pointer FILE* pointer_name; Open a File in C For opening a file in C, the fopen() function is used with the filename or file path along with the required access modes. Syntax of fopen() FILE* fopen(const char *file_name, const char *access_mode); Parameters ⚫ file_name: name of the file when present in the same directory as the source file.Otherwise, full path. Mr.U.Udayakumar, Assistant Professor, Department of Computer Science & 8 ⚫ acAceppslsic_amtioonsd(Be.:ScSCpSe)c, iSfRiMesISfTo, rRawmhapautraomperation the file is being opened.
  • 9.
    File opening modesin C Mr.U.Udayakumar, Assistant Professor, Department of Computer Science & Applications(B.Sc CS), SRMIST, Ramapuram 9
  • 10.
    Example – Createa new File // C Program to create a file #include <stdio.h> #include <stdlib.h> int main() { // file pointer FILE* fptr; // creating file using fopen() access mode "w" fptr = fopen("file.txt", "w"); // checking if the file is created if (fptr == NULL) { printf("The file is not opened. The program will " "exit now" ); exit(0); } else { printf("The file is created Successfully."); } return 0; Output The file is created Successfully. Mr.U.Udayakumar, Assistant Professor, Department of Computer Science & Applications(B.Sc CS), SRMIST, Ramapuram 10 }
  • 11.
    Reading From aFile ar); ⚫ The file read operation in C can be performed using functions fscanf() or fgets(). Both the functions performed the same operations as that of scanf and gets but with an additional parameter, the file pointer. There are also other functions we can use to read from a file. Such functions are listed below: ⚫ Example: FILE * fptr; fptr = fopen(“fileName.txt”, “r”); fscanf(fptr, "%s %s %s %d", str1, str2, str3, &ye char c = fgetc(fptr); ⚫ The getc() and some other file reading functions return EOF (End Of File) when they reach the end of the file while reading. EOF indicates the end of the file and its value is implementation-defined. Mr.U.Udayakumar, Assistant Professor, Department of Computer Science & Applications(B.Sc CS), SRMIST, Ramapuram 11
  • 12.
    Write data toa File ⚫ The file write operations can be performed by the functions fprintf() and fputs() with similarities to read operations. C programming also provides some other functions that can be used to write data to a file such as: ⚫ Example: FILE *fptr ; fptr = fopen(“fileName.txt”, “w”); fprintf(fptr, "%s %s %s %d", "We", "are", "in", 2012); fputc("a", fptr); Mr.U.Udayakumar, Assistant Professor, Department of Computer Science & Applications(B.Sc CS), SRMIST, Ramapuram 12
  • 13.
    Program to copyfrom one file to another file 13 void main() { FILE *fp,*fp1; int ch; clrscr(); fp=fopen("ex _file4.c","r"); fp1=fopen("ex_file2.c","w"); if(fp==NULL) printf(“File is not available”); ch=getc(fp); while(ch!=EOF) { putc(ch,fp1); ch=getc(fp); } fclosMe(rf.pU).;Udayakumar, Assistant Professor, Department
  • 14.
    fscanf() and fprintf() ⚫The functions fprintf() and fscanf() are similar to printf() and scanf() except that these functions operate on files and require one additional and first argument to be a file pointer. Example #include <stdio.h> main () { FILE *fp; float total; fp = fopen("da ta.txt", "w+"); if (fp == NULL) { printf("data.txt does not exist, please check!n"); exit (1); } fprintf(fp, 100); fscanf(fp, "%f", &total); fclose(fp); printf("Value of total is Mr.U.Udayakumar, Assistant Professor, Department of Computer Science & Applications(B.Sc CS), SRMIST, Ramapuram 14
  • 15.
    getc() and putc() ⚫Thefunctions getc() and putc() are equivalent to getchar() and putchar() functions ⚫Input and Output, except that these functions require an argument which is the file pointer. ⚫Function getc() reads a single character from the file which has previously been opened using a function ⚫getc(in_file); ⚫putc(c, out_file); Mr.U.Udayakumar, Assistant Professor, Department of Computer Science & Applications(B.Sc CS), SRMIST, Ramapuram 15
  • 16.
    Example #include <stdio.h> main () { charin_file[30], out_file[30]; FILE *fpin, *fpout; int c; printf("This program copies the source file to the destination file nn"); printf("Enter name of the source file :"); scanf("%30s", in_file); printf("Enter name of the destination file :"); scanf("%30s", out_file); if((fpin=fopen(in_file, "r")) == NULL) else if ((fpout=fopen(out_file, "w")) == NULL) printf("Error could not open destination file for readingn"); else { while((c =getc(fpin)) != EOF) putc(c, fpout); printf("Destination file has been copiedn"); } } printf(M"rE.Urr.Uordacyoakuulmdanr,oAtssoisptaennt Psroouferscseor,fiDleepfaortrment of Computer Science & 16 readinAgppnl"ic)a;tions(B.Sc CS), SRMIST, Ramapuram
  • 17.
    ftell() ⚫ Functions ftell()and fseek() are important in a program performing file manipulations. Function ftell() returns the current position of the file pointer in a stream. The return value is 0 or a positive integer indicating the byte offset from the beginning of an open file. long int ftell(FILE *fp); Mr.U.Udayakumar, Assistant Professor, Department of Computer Science & Applications(B.Sc CS), SRMIST, Ramapuram 17
  • 18.
    fseek() ⚫ This functionpositions the next I/O operation on an open stream to a new position relative to the current position. ⚫ int fseek(FILE *fp, long int offset, int origin); ⚫ Here fp is the file pointer of the stream on which I/O operations are carried on, offset is the number of bytes to skip over. The offset can be either positive or negative, denting forward or backward movement in the file. origin is the position in the stream to which the offset is applied, this can be one of thefollowing constants : ⚫ SEEK_SET : offset is relative to beginning of the file ⚫ SEEK_CUR : offset is relative to the current position in the file ⚫ SEEK_END : offset is relative to end of the file Mr.U.Udayakumar, Assistant Professor, Department of Computer Science & Applications(B.Sc CS), SRMIST, Ramapuram 18
  • 19.
    Example #include <stdio.h> #include <stdlib.h> charbuffer[11]; int position; main () { FILE *file_ptr; int num; if ((file_ptr = fopen("test_fil e", "w+f 10")) Mr.U.Udayakumar, Assistant Professor, Department of Computer Science & Applications(B.Sc CS), SRMIST, Ramapuram 19
  • 20.
    Example printf("Error opening test_file n"); exit(1); } fputs("1111111111", file_ptr); fputs("2222222222", file_ptr); if ( (position = fseek(file_ptr, 10, SEEK_SET)) != 0) { printf("Error in seek operation: errno n"); exit(1); } num = 11; fgets(buffer, num, file_ptr); printf("The record is %sn", buffer); fclose(file_ptr); } Mr.U.Udayakumar, Assistant Professor, Department of Computer Science & Applications(B.Sc CS), SRMIST, Ramapuram 20
  • 21.
    Thank you 21 Mr.U.Udayakumar, AssistantProfessor, Department of Computer Science & Applications(B.Sc CS), SRMIST, Ramapuram