0% found this document useful (0 votes)
768 views12 pages

UNIT-5 File Management in C: There Are Two Types of Files in C Language

File management in C allows programs to read and write files. A file pointer of type FILE is used to access files. There are functions for sequential access like fopen(), fclose(), fscanf(), fprintf(), getc(), putc(), and random access like fseek(), ftell(), rewind(). Fopen() opens a file and returns a file pointer. Fclose() closes an open file. Functions like fscanf(), fprintf(), getc(), putc() allow reading from and writing to files. Fseek() sets the file position, ftell() returns it, and rewind() resets to the beginning.

Uploaded by

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

UNIT-5 File Management in C: There Are Two Types of Files in C Language

File management in C allows programs to read and write files. A file pointer of type FILE is used to access files. There are functions for sequential access like fopen(), fclose(), fscanf(), fprintf(), getc(), putc(), and random access like fseek(), ftell(), rewind(). Fopen() opens a file and returns a file pointer. Fclose() closes an open file. Functions like fscanf(), fprintf(), getc(), putc() allow reading from and writing to files. Fseek() sets the file position, ftell() returns it, and rewind() resets to the beginning.

Uploaded by

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

UNIT-5

File management in C
 A file is a collection of data stored in one unit, identified by a filename. It can be a
document, picture, audio or video stream, data library, application, or other collection
of data.
 A file represents a sequence of bytes on the disk where a group of related data is
stored. File is created for permanent storage of data. It is a readymade structure.
 In C language, we use a structure pointer of FILE type to declare a file.
 A File can be used to store a large volume of persistent data.
 File is a permanent storage medium in which we can store the data permanently.

There are Two types of files in C language:


1. Binary file
2. Text file

Binary File Text File


The data is in the form of 0’s and The data is in the form of high level
1’s. low level language. language(English) collection of
alphabets and digits( 0-9)
Binary file is machine Human understandable and readable.
understandable and machine
readable.
Identifying errors is difficult and Errors can be identified and detect. Can
we can not detect. Modification do modifications.
is not possible.
Debugging is not easy Debugging is very easy
Binary file can not be converted Text file must convert into intermediate
into intermediate language. code or machine understandable code.
No need of language translators Here we use language translators to
convert high level code into binary
code. Ex: compilers
Binary codes are direct Execution is slow when compared with
executable codes. Execution is binary files. Because text files are not
very fast direct executable codes.
Ex: .bin, .exe, .obj, image, audio, Ex: C program, .txt, .doc, .ppt
video

Working with files


When working with files, you need to declare a pointer of type FILE. This declaration is
needed for communication between the file and the program.
FILE *fileptr;
Following are the most important file management functions available in 'C,'

File I/O functions:

getc(),putc(),getw(),putw(),fprintf(),fscanf()

Two Types of file handling functions

(1) Sequential file access functions


fopen(), fclose(),getc(),putc(),getw(),putw(),fprintf(),fscanf()

(2) Random access functions


fseek(),ftell(),rewind()

In C programming language, there different modes are available to open a file and they
are shown in the following table.
S. No. Mode Description
1 r Opens a text file in reading mode.
2 w Opens a text file in writing mode.
3 a Opens a text file in append mode.
4 r+ Opens a text file in both reading and writing mode.
5 w+ Opens a text file in both reading and writing mode. It set the
cursor position to the beginning of the file if it exists.
6 a+ Opens a text file in both reading and writing mode. The
reading operation is performed from beginning and writing
operation is performed at the end of the file.

List of all File Handling functions and purpose


Function Purpose
Sequential access functions
fopen () Creating a new file or opening an existing file
fclose () Closing a file
fscanf () Reading a block data from a file
fprintf() Writing a block of data into file
getc () Reads a single character from a file
putc () Writes a single character to a file
getw () Reads an integer from a file
putw () Writing an integer to a file
Random access functions
fseek () Sets the position of a file pointer to a specified location
ftell () Returns the current position of a file pointer
rewind () Sets the file pointer at the beginning of a file

EOF=-1
fopen()
 We use the fopen() function to create new file or to open an existing file .
 If the file does not exist create a new file with the given name.
 If the file exists, it opens an existing file.
 Once the file has been created, it can be opened, modified or deleted.
 If fopen() unable to open a file than it will return NULL to the file pointer.
Syntax:
FILE *fp ; // fp is a file pointer variable
fp = fopen (“FILE NAME ” , ”Mode”); //success full open=1000 address
fp=1000 if fopen fails fp=NULL
 fp is the pointer to the file that establishes a connection between the file and the
program.
 FILE NAME is the name of the file.
 Mode is the mode in which we want to open our file.

Example 1:Opening file in read mode


fp=fopen(“sample.txt” , ”r”); //r-read mode
1. r mode opens only an existing file.
2. If file does not exist it reports error or return NULL pointer.
3. In r mode we cannot modify or delete the file contents
4. The file pointer will be at the beginning of the file.
5. We can only retrieve data from the file

Example 2: Opening file in write mode


fp=fopen(“sample.txt” , ”w”); //w-Write mode
1. If the file does not exist it creates new file.
2. If the file exists, it erases the existing content of file and new data will
over write with old data.
3. File pointer position will be at the beginning of file
4. We can write data into file
5. The file can be modified with new data

Example 3: Opening file in append mode


fp=fopen(“sample.txt” , ”a”); //a-append mode
1. If the file does not exist it creates new file.
2. If the file exists, opens with existing content of file.
3. File pointer will be at the End of the file.(EOF= -1)
4. New data is added at the end of the file.
5. The file modified that new data is added to the existing data at the end.
6. The new data will be concatenated with the old data.

Note: fp is a file pointer is a pointer variable which can be store the address
of a file gets opened.
Note: same file can not be opened in different modes at time.

fclose()
 The file must be closed once it is opened in any mode after its use.
 Closing a file is performed using the fclose() function.
Syntax: fclose(filepointer);
Example: fclose(fp);
Here, fp is a file pointer associated with the file to be closed.
Note: Every file must be closed once we open it. To open file in any mode the must be
closed in previous mode.

getc()
 It's used to read single character from a file that has been opened in read(r) mode by
fopen() function.
 getc() function returns next requested object from the file stream on success.
Syntax: int getc(filepointer); Hello
Example: FILE *fp;
getc(fp);

putc()
 It is used to write a character to the file.
 This function is used for writing a single character in a stream along with that it
moves forward the indicator's position.
Syntax: int putc( char ch, FILE *fp); helloa
Example: FILE *fp;
char ch=’a’;
putc(ch,fp); // value of ch is copied into file which is pointed by fp

fscanf()
 fscanf() function is used to read formatted data from a file.
 fscanf() function is used to read mixed type data values form the file.

Syntax:
fscanf(FILE *fp,"format-string",&var-list); //read input from the
file
RAMU 20
SITA 16
SHEELA 23

Example:
int age;
char name[20];
fscanf (fp, “%s%d”, name, &age); //name=Ramu age=20
Where, fp is file pointer to the data type “FILE”.
Note: The fscanf() function is similar to scanf() function except the first argument
which is a file pointer that specifies the file to be read.

fprintf()
 The fprintf() function is used to write mixed data type values into the file.
 fprintf() function is used to write formatted data into a file

Syntax:
fprintf(FILE *fp,"format-string",var-list);

Example:
int age=20;
char name[20]=”ramu”;
fprintf (fp, “%s %d\n”, name, age); // ramu 20
Where, fp is file pointer to the data type “FILE”.

Random Access Functions:


fseek()
 fseek() sets the file pointer at a desired position in a file.
 fseek() function sets the file position of the stream to the given offset.
 This function returns (NULL) if successful, or else it returns a non-zero unsuccessful
value.

Syntax:
int fseek(FILE *fp, long int offset, int whence);
Parameters
 fp − This is the pointer to a FILE object that identifies the file.
 offset − This is the number of bytes to (move) offset from whence POINT.
Offset= -ve backward move
+ve forward move
 whence − This is the position from where offset is added. It is specified by one of the
following constants
s.No Whence Constant value Meaning
1 SEEK_SET 0 Beginning of file
2 SEEK_CUR 1 Current position
3 SEEK_END 2 End of file

Example:
 fseek(fp,10,SEEK_SET) OR fseek(fp,7,0)

offset=10, whence=SEEK_SET / 0
sets the file position at 10th position from the beginning of the file.
 fseek(fp,-5,SEEK_CUR) OR fseek(fp,-2,1)

offset=-5, whence= SEEK_CUR/1


The file position moved back to 5 bytes towards left from the current position of
the file.
 fseek(fp,-3,SEEK_END) or fseek(fp,-3,2)

The file position moved back to 3 bytes towards left from the End of the file.

ftell()
 ftell function is used to know current position of the file pointer.
Syntax: long int ftell(FILE *fp);
Example: ftell(fp);
rewind()
 rewind function is used to move file pointer position to the beginning of the file
where ever the cursor in the file..
Syntax: void rewind(FILE *fp)
Example: rewind(fp);

rewind(fp) === fseek(fp,0,0)


Program to illustrate fprintf() function
#include<stdio.h>
void main()
{
FILE *fp;
int rollno,n,i;
char name[25];
float percentage;

fp = fopen("student.txt","w"); //Statement 1
if(fp == NULL)
{
printf("\nCan't open file or file doesn't exist.");
exit(0);
}

Printf(“Enter n:\n”);
Scanf(“%d”,&n);
for(i=0;i<n;i++)
{
printf("\nEnter Roll, Name and Percentage :\n ");
scanf("%d%s%f",&rollno,name,&percentage);
fprintf(fp,"%d %s %f\n",rollno,name,percentage);

}
printf("\nData written successfully...");
fclose(fp);
}

Program to illustrate fscanf() function.


#include<stdio.h>
void main()

{
FILE *fp;
int rollno;
char name[25];
float percentage;
fp = fopen("student.txt","r"); //Statement 1
if(fp == NULL)
{
printf("\nCan't open file or file doesn't exist.");
exit(0);
}
printf("\nReading Data from file...\n"); //while((ch=getc(fp))!=EOF) hello
while((fscanf(fp,"%d%s%f",&rollno,name,&percentage))!=EOF)
printf("\n%d\t%s\t%f",rollno,name,percentage);
fclose(fp);
}
o/p: 101 ramu 78.9
102 sita 89.7

program: Read and display the contents of text file


#include <stdio.h>
#include <stdlib.h>
void main()
{
FILE *fp;
char ch;

fp = fopen(“Input.txt”, "w"); // creating new file

if (fp == NULL)
{
printf("Cannot open file \n");
exit(0);
}
printf("Enter any text …and stop with $ \n");

while((ch=getchar())!=’$’) //EOF=-1
putc(ch,fp);

fclose(fp);

fp = fopen(“Input.txt”, "r");
if (fp == NULL)
{
printf("Cannot open file \n");
exit(0);
}
printf(“input file data is\n”);
while ((ch=getc(fp)) !=EOF)
putchar(ch);

fclose(fp);
}

File Copying
1. Declare 2 file pointers
1.Input.txt(fp1) 2. Output.txt(fp2)
2.Create input file
3. write text into input file(fp1)
4.close fp1
5. create output file(fp2)
6. open input file in r mode(fp1)
7. read each character one by one from fp1 and copy into fp2
8. close fp1 and fp2
9.display content of output file.

program: Copy one file into another file

#include <stdio.h>
#include <stdlib.h>
void main()
{
FILE *fp1,*fp2;
char ch;
fp1 = fopen(“Input.txt”, "w");
if (fp1 == NULL)
{
printf("Cannot open input file \n");
exit(0);
}
printf("Enter any text into file …and to stop text type $ \n");

while((ch=getchar())!=’$’)
putc(ch,fp1);
fclose(fp1);

fp1 = fopen(“Input.txt”, "r");


fp2 = fopen(“Output.txt”, "w");

while ((ch=getc(fp1)) !=EOF)


putc(ch,fp2);
fclose(fp1);
fclose(fp2);

fp2 = fopen(“Output.txt”, "r");


printf(“Output file data is\n”);
while ((ch=getc(fp2)) !=EOF)
putchar(ch);
fclose(fp2);
}

File Merging

1.create file 1 and write data into file1


2. create file2 and write data into file2
3.close file1 and file2
4.create file3
5. open file1 in r mode
6.open file2 in r mode
7. copy file1 data into file3
8. copy file2 data into file3
9.close file1,file2,file3
10.display file3 data

program: Merge two files into third file

#include <stdio.h>
#include <stdlib.h>
void main()
{
FILE *fp1,*fp2,*fp3;
char ch;

fp1 = fopen(“file1.txt”, "w");


printf("Enter any text into file 1…and to stop text type $ \n");
while((ch=getchar())!=’$’)
putc(ch,fp1);
fclose(fp1);

fp2 = fopen(“file2.txt”, "w"); //creating file2


printf("Enter any text into file 2…and to stop text type $ \n");
while((ch=getchar())!=’$’) //input: hello$
putc(ch,fp2);
fclose(fp2);

fp3 = fopen(“file3.txt”, "w");


fp1 = fopen(“file1.txt”, "r");
fp2 = fopen(“file2.txt”, "r");

while (ch=getc(fp1) !=EOF)


putc(ch,fp3);

while (ch=getc(fp2) !=EOF)


putc(ch,fp3);

fclose(fp1);
fclose(fp2);
fclose(fp3);

fp3= fopen(“file3.txt”, "r");


printf(“Merged file content is\n”);
while ((ch=getc(fp3) )!=EOF)
putchar(ch);
fclose(fp3);
}
Write a program to display the first n characters of file in reverse

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
void reverse(FILE *, int );

void main()
{
FILE *fp;
int n;
char ch;

fp=fopen("input.txt","w+");
printf("Enter text….. to stop $ ::\n");
while((ch=getchar())!='$')
fputc(ch,fp);

rewind(fp);

printf("Number of chars to reverse:: ");


scanf("%d",&n);
rewind(fp);

reverse(fp,n);
rewind(fp);

printf("After reversing text is::\n");


while((ch=getc(fp))!=EOF)
putchar(ch);
fclose(fp);

void reverse(FILE *fp, int n)


{
char s[20];
int i;
for( i=0;i<n;++i)
s[i]=getc(fp);
s[n]='\0';
rewind(fp);
printf("String is\n");
printf("%s\n",s); //printing the string
while(n>0)
{
putc(s[n-1],fp);
n--;
}
}

You might also like