0% found this document useful (0 votes)
8 views

file-handling-C

The document provides an overview of file handling in C, including real-life applications, basic operations, and specific functions for reading and writing files. It details how to open, close, and manipulate files using various modes and functions, along with examples of code snippets. Additionally, it covers error handling techniques related to file operations.

Uploaded by

unnati.vaidya23
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

file-handling-C

The document provides an overview of file handling in C, including real-life applications, basic operations, and specific functions for reading and writing files. It details how to open, close, and manipulate files using various modes and functions, along with examples of code snippets. Additionally, it covers error handling techniques related to file operations.

Uploaded by

unnati.vaidya23
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 22

File Handling in C

Real-life applications

• In programming, we may require some specific input data to


be generated several numbers of times.
• Sometimes, it is not enough to only display the data on the
console. The data to be displayed may be very large, and only
a limited amount of data can be displayed on the console
• And Since the memory is volatile, it is impossible to recover
the programmatically generated data again and again.
• However, if we need to do so, we may store it onto the local
file system which is non volatile and can be accessed every
time.
Basic File Operations

• Opening a file
• Reading data from a file
• Writing data to a file
• Closing a file
C File Handling Operations

• Creating a new file: fopen()


• Opening an existing file in your system: fopen()
• Closing a file: fclose()
• Reading characters from a file: fgetc()
• Writing characters in a file: fputc()
• Reading a set of data from a file: fscanf()
• Writing a set of data in a file: fprintf()
• Reading an integral value from a file: getw()
• Writing an integral value in a file: putw()
• Setting a desired position in the file: fseek()
• Getting the current position in the file: ftell()
• Setting the position at the beginning point: rewind()
Opening a File
• A file must be “opened” before it can be used.
FILE *fp;
fp = fopen (filename, mode);
– fp is declared as a pointer to the data type FILE.
– filename is a string - specifies the name of the file.
– fopen returns a pointer to the file which is used in all
subsequent file operations.
– mode is a string which specifies the purpose of opening
the file:
“r” :: open the file for reading only
“w” :: open the file for writing only
“a” :: open the file for appending data to it
File Modes
Mode Description

r opens a text file in read mode


w opens a text file in write mode
a opens a text file in append mode
r+ opens a text file in read and write mode
w+ opens a text file in read and write mode
a+ opens a text file in read and write mode
rb opens a binary file in read mode
wb opens a binary file in write mode
ab opens a binary file in append mode
rb+ opens a binary file in read and write mode

wb+ opens a binary file in read and write mode


Examples

FILE *in, *out ;


in = fopen (“mydata.dat”, “r”) ;
out = fopen (“result.dat”, “w”);

FILE *empl ;
char filename[25];
scanf (“%s”, filename);
empl = fopen (filename, “r”) ;
Closing a File
• After all operations on a file have been
completed, it must be closed.
– Ensures that all file data stored in memory buffers
are properly written to the file.
• General format: fclose (file_pointer) ;
FILE *xyz ;
xyz = fopen (“test.txt”, “w”) ;
…….
fclose (xyz) ;
Files and Streams
• Read/Write functions in standard library
– getc
• Reads one character from a file
• Takes a FILE pointer as an argument
• fgetc( stdin ) equivalent to getchar()
– putc
• Writes one character to a file
• Takes a FILE pointer and a character to write as an
argument
• fputc( 'a', stdout ) equivalent to putchar(
'a' )
– fscanf / fprintf
• File processing equivalents of scanf and printf
Read/Write Operations on Files

• The simplest file input-output (I/O) function are getc and putc.
• getc is used to read a character from a file and return it.
char ch; FILE *fp;
…..
ch = getc (fp) ;
– getc will return an end-of-file marker EOF, when the end of
the file has been reached.
• putc is used to write a character to a file.
char ch; FILE *fp;
……
putc (ch, fp) ;
Jaypee Institute of Information Technology University,
Noida
fscanf and fprintf
• We can also use the file versions of scanf and printf, called fscanf
and fprintf.
• General format:
fscanf (file_pointer, control_string, list) ;
fprintf (file_pointer, control_string, list) ;
• Examples:
fscanf (fp, “%d %s %f”, &roll, dept_code, &cgpa) ;
fprintf (out, “\nThe result is: %d”, xyz) ;
fprintf
• Used to print to a file
• It is like printf, except first argument is a FILE pointer (pointer to the file
you want to print in)
Some Points
• How to check EOF condition when using
fscanf?
– Use the function feof
if (feof (fp))
printf (“\n Reached end of file”) ;
• How to check successful open?
– For opening in “r” mode, the file must exist.
if (fp == NULL)
printf (“\n Unable to open file”) ;
• #include <stdio.h>
//reading contents from one file and printing on console
int main()
{
FILE *fp;
int n;
fp=fopen("d1.txt","r");
if(fp==NULL)
printf("error");
fscanf(fp,"%d",&n);
printf("%d",n);
}
Example program: writing into a text file

#include <stdio.h>
#include <stdlib.h>
int main()
{
int num;
FILE *fptr; // use appropriate location if you are
using MacOS or Linux
fptr = fopen("C:\\program.txt","w");
if(fptr == NULL)
{
printf("Error!");
exit(1);
}
printf("Enter num: ");
scanf("%d",&num);
fprintf(fptr,"%d",num);
fclose(fptr);
return 0;
}
//writing contents from one file and writing contents into
another file
int main()
{
char num[10];
FILE *fptr,*fptr1; // use appropriate location if you are
using MacOS or Linux
fptr1=fopen("sup1.txt","r");
fptr = fopen("sup.txt","w");
if(fptr == NULL)
{
printf("Error!");
exit(1);
}
fscanf(fptr1,"%s",num);
fprintf(fptr,"%s",num);
fclose(fptr);
return 0;
}
Program to read/write using getc/putc
#include <stdio.h>
main()
{ FILE *fp1;
char c;
f1= fopen(“INPUT”, “w”); /* open file for writing */

while((c=getchar()) != EOF) /*get char from keyboard until CTL-Z*/


putc(c,f1); /*write a character to INPUT */

fclose(f1); /* close INPUT */


f1=fopen(“INPUT”, “r”); /* reopen file */

while((c=getc(f1))!=EOF) /*read character from file INPUT*/


printf(“%c”, c); /* print character to screen */

fclose(f1);
} /*end main */
getw() and putw()
• handle one integer at a time
• syntax: putw(i,fp1);
– i : an integer variable
– fp1 : pointer to file ipened with mode w
• syntax: i = getw(fp2);
– i : an integer variable
– fp2 : pointer to file opened with mode r
• file pointer moves by one integer position, data stored in binary format native to
local system
• getw() returns end-of-file marker EOF when file end reached
1. Text files (ASCII) :Text files contain ASCII codes of digits, alphabetic and symbols.
2. Binary files: Binary file contains collection of bytes (0’s and 1’s). Binary files are
compiled version of text files.
C program using getw, putw,fscanf, fprintf
#include <stdio.h> #include <stdio.h>
main() main()
{ int i,sum1=0; { int i, sum2=0;
FILE *f1; FILE *f2;
/* open files */ /* open files */
f1 = fopen("int_data.bin","w"); f2 = fopen("int_data.txt","w");
/* write integers to files in binary /* write integers to files in binary and
and text format*/ text format*/
for(i=10;i<15;i++) putw(i,f1); for(i=10;i<15;i++) printf(f2,"%d\n",i);
fclose(f1); fclose(f2);
f1 = fopen("int_data.bin","r"); f2 = fopen("int_data.txt","r");
while((i=getw(f1))!=EOF) while(fscanf(f2,"%d",&i)!=EOF)
{ sum1+=i; { sum2+=i; printf("text file: i=%d\
printf("binary file: i=%d\n",i); n",i);
} /* end while getw */ } /*end while fscanf*/
printf("binary sum=%d,sum1); printf("text sum=%d\n",sum2);
fclose(f1); fclose(f2);
} }
On execution of previous Programs
$ ./a.out $ ./a.out
binary file: i=10 text file: i=10
binary file: i=11 text file: i=11
binary file: i=12 text file: i=12
text file: i=13
binary file: i=13
text file: i=14
binary file: i=14 text sum=60
binary sum=60, $ more int_data.bin
$ cat int_data.txt ^@^@^@^K^@^@^@^L^@^@^@^
M^@^@^@^N^@^@^@
10
$
11
12
13
14
Errors that occur during I/O

• Typical errors that occur

– trying to read beyond end-of-file

– trying to use a file that has not been opened

– perform operation on file not permitted by ‘fopen’ mode

– open file with invalid filename

– write to write-protected file


Error handling
• given file-pointer, check if EOF reached, errors while handling
file, problems opening file etc.
• check if EOF reached: feof()
• feof() takes file-pointer as input, returns nonzero if all data
read and zero otherwise
if(feof(fp))
printf(“End of data\n”);

• ferror() takes file-pointer as input, returns nonzero integer if


error detected else returns zero
if(ferror(fp) !=0)
printf(“An error has occurred\n”);
Error while opening file

• if file cannot be opened then fopen returns a NULL pointer

• Good practice to check if pointer is NULL before proceeding

fp = fopen(“input.dat”, “r”);

if (fp == NULL)
printf(“File could not be opened \n ”);

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy