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

File Handling in C

File handling in C programming language. Proper code and examples are included kindly go thru the same for more details on File handling

Uploaded by

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

File Handling in C

File handling in C programming language. Proper code and examples are included kindly go thru the same for more details on File handling

Uploaded by

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

File Management in C

Console oriented Input/Output


Console oriented – use terminal (keyboard/screen)

scanf(“%d”,&i) – read data from keyboard

printf(“%d”,i) – print data to monitor

Suitable for small volumes of data

Data lost when program terminated


Real-life applications
Large data volumes

E.g. physical experiments (CERN collider), human


genome, population records etc.

Need for flexible approach to store/retrieve data

Concept of files
Files
File – place on disc where group of related data is
stored
E.g. your C programs, executables

High-level programming languages support file


operations
Naming
Opening
Reading
Writing
Closing
Defining and opening file
To store data file in secondary memory (disc) must
specify to OS

Filename (e.g. sort.c, input.data)

Data structure (e.g. FILE)

Purpose (e.g. reading, writing, appending)


Filename
String of characters that make up a valid filename for
OS

May contain two parts


Primary
Optional period with extension

Examples: a.out, prog.c, temp, text.out


The Stream
A very important concept in C is the stream. In C, the
stream is a common, logical interface to the various devices
that comprise the computer.
In its most common form, a stream is a logical interface to
a file.
As C defines the term "file", it can refer to a disk file, the
screen, the keyboard, a port, a file on tape, and so on.
Although files differ in form and capabilities, all streams
are the same.
The stream provides a consistent interface and to the
programmer one hardware device will look much like
another.
Types of Streams.
A stream is linked to a file using an open operation. A
stream is disassociated from a file using a close operation.
The current location, also referred to as the current
position, is the location in a file where the next file access
will occur.
There are two types of streams:
Text (used with ASCII characters some character
translation takes place, may not be one-to-one
correspondence between stream and what's in the file)
Binary (used with any type of data, no character
translation, one-to-one between stream and file).
FILE structure in C
C Provides smart way to manipulate data using
streams

In stdio.h header file FILE structure is defined

FILE structure provides us the necessary information


about a FILE or stream which performs input and
output operations.
C FILE Structure Defined in
<stdio.h>
 Structure :
 typedef struct
{
 short level ;
 short token ;
 short bsize ;
 char fd ;
 unsigned flags ;
 unsigned char hold ;
 unsigned char *buffer ;
 unsigned char * curp ;
 unsigned istemp;
 }FILE ;
Filename
String of characters that make up a valid filename for
OS

May contain two parts


Primary
Optional period with extension

Examples: a.out, prog.c, temp, text.out


General format for opening file
FILE *fp; /*variable fp is pointer to type FILE*/

fp = fopen(“filename”, “mode”);
/*opens file with name filename , assigns identifier to fp */

fp
contains all information about file
Communication link between system and program
Mode can be
r open file for reading only
w open file for writing only
a open file for appending (adding) data
Different modes
Writing mode
if file already exists then contents are deleted,
else new file with specified name created
Appending mode
if file already exists then file opened with contents safe
else new file created
Reading mode
if file already exists then opened with contents safe
else error occurs.

FILE *p1, *p2;


p1 = fopen(“data”,”r”);
p2= fopen(“results”, w”);
Additional modes
r+ open to beginning for both reading/writing

w+ same as w except both for reading and writing

a+ same as ‘a’ except both for reading and writing


Closing a file
File must be closed as soon as all operations on it
completed

Ensures
All outstanding information associated with file flushed
out from buffers
All links to file broken
Accidental misuse of file prevented

If want to change mode of file, then first close and


open again
Closing a file
Syntax: fclose(file_pointer);

Example:

FILE *p1, *p2;


p1 = fopen(“INPUT.txt”, “r”);
p2 =fopen(“OUTPUT.txt”, “w”);
……..
……..
fclose(p1);
fclose(p2);

pointer can be reused after closing


Input/Output operations on
files
C provides several different functions for
reading/writing

fgetc() – read a character


fputc() – write a character
getw() – read integer
putw() – write integer
fgets()-read a line
fputs()-write a line.
fgetc()
int fgetc(FILE *pointer)
pointer: pointer to a FILE object that identifies
the stream on which the operation is to be performed.
C Program
 int main ()
 {
 // open the file
 FILE *fp = fopen("test.txt","r");

 // Return if could not open file
 if (fp == NULL)
 return 0;
 do
 {
 // Taking input single character at a time
 char c = fgetc(fp);
 // Checking for end of file
 if (feof(fp))
 break ;
 printf("%c", c);
 } while(1);

 fclose(fp);
 return(0);
 }
Output:

The entire content of file is printed character by


character till end of file. It reads newline character
as well.
fputc()
fputc() is used to write a single character at a time to a
given file.

It writes the given character at the position denoted by


the file pointer and then advances the file pointer.

This function returns the character that is written in


case of successful write operation else in case of error
EOF is returned.
Syntax
int fputc(int char, FILE *pointer)
char: character to be written.
This is passed as its int promotion.
pointer: pointer to a FILE object that identifies the
stream where the character is to be written.
 #include<stdio.h>
 int main()
 {
 int i = 0;
 FILE *fp = fopen("output.txt","w");

 // Return if could not open file
 if (fp == NULL)
 return 0;
 char string[] = "good bye", received_string[20];
 for (i = 0; string[i]!='\0'; i++)

 // Input string into the file
 // single character at a time
 fputc(string[i], fp);
 fclose(fp);
 fp = fopen("output.txt","r");
 // Reading the string from file
 fgets(received_string,20,fp);
 printf("%s", received_string);
 fclose(fp);
 return 0;
 }
Output
good bye
The putw() function

The putw() function is used to write integers to the


file.
putw(int number, FILE *fp);
 #include<stdio.h>
 void main()
 {
 FILE *fp;
 int num;
 char ch='n‘;
 fp = fopen("file.txt","w"); //Statement 1
 if(fp == NULL)
 {
 printf("\nCan't open file or file doesn't exist.");
 exit(0);
 }
 do //Statement 2
 {
 printf("\nEnter any number : ");
 scanf("%d",&num);

 putw(num,fp);

 printf("\nDo you want to another number : ");


 ch = getche();
 }while(ch=='y'||ch=='Y');

 printf("\nData written successfully...");

 fclose(fp);
 }
Output :

 Enter any number : 78


 Do you want to another number : y
 Enter any number : 45
 Do you want to another number : y
 Enter any number : 63
 Do you want to another number : n
 Data written successfully...
The getw() function
The getw() function is used to read integer value form
the file.
int getw(FILE *fp);
 #include<stdio.h>
 void main()
 {
 FILE *fp;
 int num;
 fp = fopen("file.txt","r"); //Statement 1
 if(fp == NULL)
 {
 printf("\nCan't open file or file doesn't exist.");
 exit(0);
 }
 printf("\nData in file...\n");

 while((num = getw(fp))!=EOF) //Statement 2


 printf("\n%d",num);
 fclose(fp);
 }
Output :

 Data in file...
 78
 45
 63
Another C program using getw, putw
#include <stdio.h>
main()
{ int i,sum1=0;
FILE *f1;
/* open files */
f1 = fopen("int_data.bin","w");
/* write integers to files in binary and text format*/
for(i=10;i<15;i++)
putw(i,f1);
fclose(f1);
f1 = fopen("int_data.bin","r");
while((i=getw(f1))!=EOF)
{ sum1+=i;
printf("binary file: i=%d\n",i);
} /* end while getw */
printf("binary sum=%d,sum1);
fclose(f1);
}
fgets()

It reads a line from the specified stream and stores it into


the string pointed to by str. It stops when either (n-1)
characters are read, the newline character is read, or the
end-of-file is reached, whichever comes first.
 Syntax :
 char *fgets(char *str, int n, FILE *stream)
 str : Pointer to an array of chars where the string read is copied.
 n : Maximum number of characters to be copied into str
 (including the terminating null-character).
 *stream : Pointer to a FILE object that identifies an input stream.
 stdin can be used as argument to read from the standard input.

 returns : the function returns str


C program to illustrate

#include <stdio.h>
#define MAX 15
int main()
{
 char buf[MAX];
 fgets(buf, MAX, stdin);
 printf("string is: %s\n", buf);
 return 0;
}
Output
Input:
Hello and welcome to GeeksforGeeks

Output:
Hello and welc
Fputs()
int fputs(const char *str, FILE *stream)
Parameters
str − This is an array containing the null-terminated
sequence of characters to be written.
stream − This is the pointer to a FILE object that
identifies the stream where the string is to be written.
Return Value
This function returns a non-negative value, or else on
error it returns EOF.
C program to illustrate
#include <stdio.h>

int main () {
 FILE *fp;
 fp = fopen("file.txt", "w+");
 fputs("This is c programming.", fp);
 fputs("This is a system programming language.", fp);
 fclose(fp);
 return(0);
}
Output
This is c programming.This is a system programming
language.

You might also like