0% found this document useful (0 votes)
24 views8 pages

Unit-5 Part 2

functions in c

Uploaded by

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

Unit-5 Part 2

functions in c

Uploaded by

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

Unit-5

File:
A File represents a sequence of bytes on the disk where a group of related data is stored.
Files allow us to store our data in a permanent form.
 Simply a File is organized collection of data. It represents data that is arranged in a specific
format.
 Files are stored in secondary memory such as hard disk, CD or DVD.
 Every file has a name. Every operating system uses a set of rules for naming its files.
 C supports many operations on files as given below:
 Creating a file / Opening a file
 Reading data from a file
 Writing data to a file
 Closing a file
Types of files:
Depending upon the format in which data is stored, files are primarily categorized into two types:
1. Text File 2. Binary File
1. Text Files:
 A Text file stores textual information like alphabets, numbers, special symbols etc., These
text files have the extension “.txt” in their names.
Eg: student.txt, emp.txt etc.,
 The C language supports various operations on text files such as creating a new text file,
opening a text file, reading data from a text file, writing data to a text file and closing a
text file.
2. Binary Files:
 A Binary file stores the information in binary form. (0s and 1s). We need not convert the
binary files whereas text files need conversion from text to binary form.
 Any file which stores data in the form of bytes is known as binary file.
 Every executable file generated by C compiler is a binary file. ( .exe )
 C supports various operations on binary files such as reading data from a binary file,
writing data to a binary file, appending data to a binary files etc.,

Creating Files:
 The C programming language provides many standard library functions for file input & output.
These functions are available in the header file <stdio.h>.
 For C file I/O, you need to create a FILE pointer, which lets the program keep track of the file
being accessed.
 A FILE pointer is a pointer to a structure that contains several pieces of information about the
file.
 We can create a FILE pointer as follows:

FILE *fp;
Opening Files:
 We can open a file for different purposes. The purpose of opening a file should be given to the
program through the use of modes.
 The following are the modes that we can use to open files:

File Opening Modes

r – open file for reading only

w – open file for writing only

a – open file for appending data to it at the end of the file.

+ - Add symbol to allow read/write access

b – Open in binary mode

 To open a file, we have to use ‘fopen()’ function by providing the file name and the mode as
parameters.
 Syntax: fopen(filename, mode);

 The fopen() function returns a FILE pointer that contains information about the file being
opened.
Example:
FILE *fp1, *fp2;
fp1=fopen(“data.txt”, “r”);
fp2=fopen(“content.txt”, “w”);

Files Page 1
Unit-5

Closing Files:
 A file must be closed soon after all the operations on it have been completed.
 When a file is closed, all the information outstanding associated with the file is flushed out from
buffers and all links to the file are broken.
 To close a file, we have to use the fclose() function
 Syntax:
fclose(FILE* fp);

 It returns 0 on success and returns EOF if any errors are detected.

Input / Output Operations on files:


 The input operation on a file means to read the contents of it. The output operation on a file
means to write the data to it.
 The following is the list of functions used to perform read and write operations on files.

I/O Description Prototype Example


function
getc() Reads a single character getc(FILE *fp) ch=getc(fp)
from a file
putc() Writes a single character to a putc(int char, FILE *fp) putc(ch)
file or on standard Output
gets() Reads a group of character gets(FILE *fp) gets(ch)
from a file
puts() Writes a group of character to puts(int char, FILE *fp) puts(ch,fp)
a file or on standard Output
getw() Reads an integer from a file getw(FILE *fp); ch=getw(fp)

putw() Writing an integer to a file putw(int number, FILE *fp); putw(ch,fp)

fputc() Write a single character into fputc(int char, FILE *fp; fputc(ch,fp)
file.
fgetc() Returns a single character fgetc(FILE *fp) ch=fgetc(fp)
from the file.
fputs() Writes a line of characters fputs(char *string, FILE *fp) fputs(ch,fp)
into file
fgets() Reads a line of characters fgets(char *string, int n, FILE fgets(ch,80,fp)
from file. *fp)
fprintf() Writing a block of data to a fprintf(FILE *fp, const char fprintf(fp,%s,ch)
file *format, variables)
fscanf() Reading a block data from a fscanf(FILE *fp, const char fscanf(fp,%s,ch)
file *format, variables)

Formatted input / output:


 The formatted input / output functions can handle a group of data simultaneously. Most C
compilers support two formatted I/O functions ‘fprintf()’ and ‘fscanf()’.
 The functions ‘fprintf()’ and ‘fscanf()’ are similar to ‘printf()’ and ‘scanf()’
functions except they work for files also.
 These functions take a FILE pointer as the first argument. This FILE pointer specifies the file to
be used.
 These two functions are defined in ‘stdio.h’ header file.

 The fprintf() function:


 The general form of the ‘fprintf()’ function is as follows:
int fprintf(FILE *fp, const char* controlString, list );


Here ‘fp’ is the FILE pointer associated with a file that has been opened for reading or
writing.
 The ‘controlString’ contains format specifiers and the list may include variables,
constants, strings etc.,
 It uses same format specifiers as printf() but it sends output to the specified stream
‘fp’.
 The fprintf() returns the number of bytes output. It returns ‘EOF’ on error.
Eg: fprintf(fp, “%s \t %d \t %f”, “Raju”, 20, 8.2);

Files Page 2
Unit-5

 The fscanf() function:


 The general form of the ‘fscanf()’ function is as follows:
int fscanf(FILE *fp, const char* controlString, list );

 Here ‘fp’ is the FILE pointer associated with a file that has been opened for reading or
writing.
 The ‘controlString’ contains format specifiers and the list may include variables,
constants, strings etc.,
 It uses same format specifiers as scanf() but it reads input from the specified stream
‘fp’.
 The fscanf() returns the number of input fields that are successfully scanned, converted
& stored. It returns ‘EOF’ on error.
Eg: fscanf(fp, “%s %d %f”, &name, &age, &points);
Random access to files:
Random accessing of files can also be possible in C with the help of the following functions:
i) fseek()
ii) ftell()
iii) rewind()
i) fseek():
 This function is used to move the file position to a desired location within the file.
 The prototype of this function is defined in ‘stdio.h’ header file. The general form of
fseek() function is given below:
int fseek(FILE *fp, long offset, int position);

 Here ‘fp’ is the FILE pointer associated with a file that has been opened for reading or
writing.
 The ‘offset’ is a number or variable of type ‘long’. It specifies the number of bytes to
be moved from the location specified by ‘position’.
 The ‘position’ is used to set the seek starting position. It takes one of the following
values:
S.NO VALUE MEANING

Seeks from the beginning


1 SEEK_SET (0)
of the file
Seeks from the current
2 SEEK_CUR (1)
position
Seeks from the end of the
3 SEEK_END (2)
file
Eg: fseek(fp, m, SEEK_CUR); (or) fseek(fp, m, 1);
The above statement indicates moving forward ‘m’ bytes from the current position.
Eg: fseek(fp, -m, SEEK_END); (or) fseek(fp, m, 2);
The above statement means moving backward by ‘m’ bytes from the end of the file.
ii) ftell():
 The ‘ftell()’ function takes a file pointer and return a ‘long’ value that indicates the
current file pointer position. It returns -1 on error.
 This function is useful in saving the current position of a file.
 The prototype of this function is defined in ‘stdio.h’ header file. The general form of
ftell() function is given below:
long ftell(FILE *fp);

 Here ‘fp’ is the FILE pointer associated with a file that has been opened for reading or
writing.

Eg: n=ftell(fp);
Here ‘n’ is a variable of type ‘long’.
iii) rewind():
 The ‘rewind()’ function takes a file pointer and repositions the file pointer to the
beginning of the file.
 The prototype of this function is defined in ‘stdio.h’ header file. The general form of
rewind() function is given below:
 Here ‘fp’ is the FILE pointer associated with a file that has been opened for reading or
writing.
void rewind(FILE *fp);

Eg: rewind(fp);
n=ftell(fp); /* n contains 0 */

Files Page 3
Unit-5

Error handling during I/O operations:


 If an error occurs in our program, the program may behave abnormally. If we check such errors,
we can take corrective measures.
 We have two status inquiry functions to detect I/O errors in the files. They are:
i) feof()
ii) ferror()
i) feof():
 The ‘feof()’ function can be used to test for an end of file condition.
 The ‘feof()’ function takes a FILE pointer as argument and it returns a non zero
integer if the file reaches end-of-file condition otherwise it returns zero.
 The prototype of this function is defined in ‘stdio.h’ header file. The general form of
feof() function is given below:

. int feof(FILE *fp);

Eg: if(feof(fp)){
printf(“\n End of data”);
}
ii) ferror ():
 The ‘ferror()’ function reports the status of the file indicated.
 The ‘ferror()’ function takes a FILE pointer as argument and it returns a non zero
integer if an error has been detected up to that point. It returns zero otherwise.
 The prototype of this function is defined in ‘stdio.h’ header file. The general form of
ferror() function is given below:
int ferror(FILE *fp);

Eg: if(ferror(fp)!=0){
printf(“\n An error has been occured”);

Examples:
1. Write a Program to creates a file & reads data and store it into the file
#include<stdio.h>
main(){
FILE *fp;
char c;
fp=fopen("file1.txt", "w");
printf("File created successfully!");
printf("\n Enter data: \n");
while((c=getchar())!=EOF)
{
putc(c, fp);
}
fclose(fp);
}
Output:

2. Write a C program to open a file and displays the content of a file.


#include<stdio.h>
main(){
FILE *fp;
char c;
fp=fopen("file1.txt", "r");
if(fp==NULL)
printf("\n Cannot open the file");
else{
printf("\n The contents of the file are: \n");
while((c=getc(fp))!=EOF){
printf("%c", c);
}
fclose(fp);
}
}
Output

Files Page 4
Unit-5
3. Write a C Program to copy content of one file to another file.
#include<stdio.h>
main()
{
FILE *fp1, *fp2;
char file1[10], file2[10];
int ch;
printf("\n Enter source file name: ");
gets(file1);
printf("\n Enter target file name: ");
gets(file2);
fp1 = fopen(file1, "r");
if(fp1==NULL)
{
printf("\n File %s cannot be opened", file1);
}
else
{
fp2 = fopen(file2, "w");
printf("\n Copying started form %s to %s.....\n", file1, file2);
while((ch=getc(fp1))!=EOF)
{
putc(ch, fp2);
}
fclose(fp1);
fclose(fp2);
printf("\n Copying completed");
}
printf("\n After copying .....\n");
printf("\n Contents of the file %s :\n", file2);
fp2=fopen(file2, "r");
while((ch=getc(fp2))!=EOF)
printf("%c", ch);
fclose(fp2);
}
Output

4. Write a C Program to merge two files and store content in another file.
main()
{
FILE *fp1,*fp2,*fp3;
char c,f1[20],f2[20],f3[20];
printf("\nEnter first file name\n");
gets(f1);
printf("\nEnter second file name\n");
gets(f2);
printf("\nEnter destination file name\n");
gets(f3);
fp1=fopen(f1, "w");
if(fp1==NULL)
{
printf("\n Cannot create file");
}
else
{
printf("\n\nFile created successfully with filename %s ",f1);
printf("\n\nEnter data: \n");
while((c=getchar())!=EOF)
{
putc(c, fp1);
}
fclose(fp1);
}
fp2=fopen(f2, "w");
if(fp2==NULL)
{

Files Page 5
Unit-5
printf("\n Cannot create file");
}
else
{
printf("\n\nFile created successfully with filename %s ",f2);
printf("\n\nEnter data: \n");
while((c=getchar())!=EOF)
{
putc(c, fp2);
}
fclose(fp2);
}
fp1=fopen(f1, "r");
fp2=fopen(f2, "r");
fp3=fopen(f3, "w");
if(fp3==NULL)
{
printf("\n Cannot create file");
}
else
{
while((c=fgetc(fp1))!=EOF)
{
fputc(c, fp3);
}
while((c=fgetc(fp2))!=EOF)
{
fputc(c, fp3);
}
printf("\n\nFiles Merged completed\n\n");
fclose(fp3);
}
fp3=fopen(f3,"r");
printf("\n\nAfter Files Merging %s content :\n\n",f3);
while((c=getc(fp3))!=EOF)
{
printf("%c", c);
}
fclose(fp1);
fclose(fp2);
fclose(fp3);
}

Output

5. Write a C program to reverse the contents in a file.


#include<stdio.h>
int main()
{
FILE *fp;
char ch;
int i=0,pos;
fp=fopen("file1.txt","r");
if(fp==NULL)
{
printf("File does not exist..");

Files Page 6
Unit-5

}
fseek(fp,0,SEEK_END);
pos=ftell(fp);
while(i<pos)
{
i++;
fseek(fp,-i,SEEK_END);
printf("%c",fgetc(fp));
}
return 0;
}
Output:

Original file file1.txt:

6. Write a C program to count number of characters, words and lines in a file


#include <stdio.h>
int main()
{
FILE * fp;
char ch;
int ccount=0, wcount=0, lcount=0;
fp = fopen("file2.txt", "r");
if(fp==NULL)
{
printf("File does not exist..");
}
while((ch = getc(fp))!= EOF)
{
ccount=ccount+1;

if (ch == '\n'||ch=='\0')
{
lcount=lcount+1;;
}

if (ch == ' '||ch=='\n')


{
wcount=wcount+1;
}
}
printf("\n");
if(ccount>0)
{
wcount++;
lcount++;

Files Page 7
Unit-5

}
printf("Total characters = %d\n", ccount);
printf("Total words = %d\n", wcount);
printf("Total lines = %d\n", lcount);
fclose(fp);
}
Output:

Files Page 8

You might also like