0% found this document useful (0 votes)
20 views16 pages

Files in C

Uploaded by

PILLAREDDY Reddy
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)
20 views16 pages

Files in C

Uploaded by

PILLAREDDY Reddy
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/ 16

FILES IN C

Generally, a file is used to store user data in a computer. In other words, computer stores the
data using files. we can define a file as follows...
Definition:
File is a collection of data that stored on secondary memory like hard disk of a computer.
C programming language supports two types of files and they are as follows...
 Text Files (or) ASCII Files
 Binary Files
Text File (or) ASCII File - The file that contains ASCII codes of data like digits, alphabets
and symbols is called text file (or) ASCII file.
Binary File - The file that contains data in the form of bytes (0's and 1's) is called as binary
file. Generally, the binary files are compiled version of text files.
File Operations in C
The following are the operations performed on files in c programming language...
1. Creating (or) Opening a file
2. Reading data from a file
3. Writing data into a file
4. Closing a file
All the above operations are performed using file-handling functions available in C. We
discuss file-handling functions in the next topic.
Creating (or) Opening a file
To create a new file or open an existing file, we need to create a file pointer of FILE type.
Following is the sample code for creating file pointer.
File *f_ptr ;
We use the pre-defined method fopen() to create a new file or to open an existing file. There
are different modes in which a file can be opened.
Consider the following code.
File *f_ptr ;
f_ptr = fopen("abc.txt", "w") ;
The above example code creates a new file called abc.txt if it does not exists otherwise it is
opened in writing mode.
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 wirting 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 begining 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.

Reading from a file


The reading from a file operation is performed using the following pre-defined file handling
methods.
1. getc()
2. getw()
3. fscanf()
4. fgets()
5. fread()
getc( *file_pointer ) –
This function is used to read a character from specified file which is opened in reading mode.
It reads from the current position of the cursor. After reading the character, the cursor will be
at next character.
Example Program to illustrate getc() in C.
#include<stdio.h>
#include<conio.h>
int main(){
FILE *fp;
char ch;
clrscr();
fp = fopen("MySample.txt","r");
printf("Reading character from the file: %c\n",getc(fp));
ch = getc(fp);
printf("ch = %c", ch);
fclose(fp);
getch();
return 0;
}
getw( *file_pointer ) –
This function is used to read an integer value form the specified file which is opened in
reading mode. If the data in file is set of characters then it reads ASCII values of those
characters.
Example Program to illustrate getw() in C.
#include<stdio.h>
#include<conio.h>
int main(){
FILE *fp;
int i,j;
clrscr();
fp = fopen("MySample.txt","w");
putw(65,fp); // inserts A
putw(97,fp); // inserts a
fclose(fp);
fp = fopen("MySample.txt","r");
i = getw(fp); // reads 65 - ASCII value of A
j = getw(fp); // reads 97 - ASCII value of a
printf("SUM of the integer values stored in file = %d", i+j); // 65 + 97 = 162
fclose(fp);
getch();
return 0;
}

fscanf( *file_pointer, typeSpecifier, &variableName ) –


This function is used to read multiple datatype values from specified file which is opened in
reading mode.
Example Program to illustrate fscanf() in C.
#include<stdio.h>
#include<conio.h>
int main(){
char str1[10], str2[10], str3[10];
int year;
FILE * fp;
clrscr();
fp = fopen ("file.txt", "w+");
fputs("We are in 2016", fp);
rewind(fp); // moves the cursor to begining of the file
fscanf(fp, "%s %s %s %d", str1, str2, str3, &year);
printf("Read String1 - %s\n", str1 );
printf("Read String2 - %s\n", str2 );
printf("Read String3 - %s\n", str3 );
printf("Read Integer - %d", year );
fclose(fp);
getch();
return 0;
}
fgets( variableName, numberOfCharacters, *file_pointer ) –
This method is used for reading a set of characters from a file which is opened in reading
mode starting from the current cursor position. The fgets() function reading terminates with
reading NULL character.
Example Program to illustrate fgets() in C.
#include<stdio.h>
#include<conio.h>
int main(){
FILE *fp;
char *str;
clrscr();
fp = fopen ("file.txt", "r");
fgets(str,6,fp);
printf("str = %s", str);
fclose(fp);
getch();
return 0;
}
fread( source, sizeofReadingElement, numberOfCharacters, FILE *pointer ) –
This function is used to read specific number of sequence of characters from the specified
file which is opened in reading mode.
Example Program to illustrate fgets() in C.
#include<stdio.h>
#include<conio.h>
int main(){
FILE *fp;
char *str;
clrscr();
fp = fopen ("file.txt", "r");
fread(str,sizeof(char),5,fp);
str[strlen(str)+1] = 0;
printf("str = %s", str);
fclose(fp);
getch();
return 0;
}
Writing into a file
The writing into a file operation is performed using the following pre-defined file handling
methods.
1. putc()
2. putw()
3. fprintf()
4. fputs()
5. fwrite()
putc( char, *file_pointer ) –
This function is used to write/insert a character to the specified file when the file is opened in
writing mode.
Example Program to illustrate putc() in C.
#include<stdio.h>
#include<conio.h>
int main(){
FILE *fp;
char ch;
clrscr();
fp = fopen("C:/TC/EXAMPLES/MySample.txt","w");
putc('A',fp);
ch = 'B';
putc(ch,fp);
fclose(fp);
getch();
return 0;
}
putw( int, *file_pointer ) - This function is used to writes/inserts an integer value to the
specified file when the file is opened in writing mode.
Example Program to illustrate putw() in C.
#include<stdio.h>
#include<conio.h>
int main(){
FILE *fp;
int i;
clrscr();
fp = fopen("MySample.txt","w");
putw(66,fp);
i = 100;
putw(i,fp);
fclose(fp);
getch();
return 0;
}
fprintf( *file_pointer, "text" ) –
This function is used to writes/inserts multiple lines of text with mixed data types (char, int,
float, double) into specified file which is opened in writing mode.
Example Program to illustrate "fprintf()" in C.
#include<stdio.h>
#include<conio.h>
int main(){
FILE *fp;
char *text = "\nthis is example text";
int i = 10;
clrscr();
fp = fopen("MySample.txt","w");
fprintf(fp,"This is line1\nThis is line2\n%d", i);
fprintf(fp,text);
fclose(fp);
getch();
return 0;
}
fputs( "string", *file_pointer ) –
This method is used to insert string data into specified file which is opened in writing mode.
Example Program to illustrate fputs() in C.
#include<stdio.h>
#include<conio.h>
int main(){
FILE *fp;
char *text = "\nthis is example text";
clrscr();
fp = fopen("MySample.txt","w");
fputs("Hi!\nHow are you?",fp);
fclose(fp);
getch();
return 0;
}
fwrite( “StringData”, sizeof(char), numberOfCharacters, FILE *pointer ) - This function is
used to insert specified number of characters into a binary file which is opened in writing
mode.

Example Program to illustrate fwrite() in C.


#include<stdio.h>
#include<conio.h>
int main(){
FILE *fp;
char *text = "Welcome to C Language";
clrscr();
fp = fopen("MySample.txt","wb");
fwrite(text,sizeof(char),5,fp);
fclose(fp);
getch();
return 0;
}
Closing a file
Closing a file is performed using a pre-defined method fclose().
fclose( *f_ptr )
The method fclose() returns '0'on success of file close otherwise it returns EOF (End Of File).
Cursor Positioning Functions in Files
C programming language provides various pre-defined methods to set the cursor position in
files. The following are the methods available in c, to position cursor in a file.
1. ftell()
2. rewind()
3. fseek()
ftell( *file_pointer ) –
This function returns the current position of the cursor in the file.
Example Program to illustrate ftell() in C.
#include<stdio.h>
#include<conio.h>
int main(){
FILE *fp;
int position;
clrscr();
fp = fopen ("file.txt", "r");
position = ftell(fp);
printf("Cursor position = %d\n",position);
fseek(fp,5,0);
position = ftell(fp);
printf("Cursor position = %d", position);
fclose(fp);
getch();
return 0;
}

rewind( *file_pointer ) –

This function is used reset the cursor position to the beginning of the file.
Example Program to illustrate rewind() in C.
#include<stdio.h>
#include<conio.h>
int main(){
FILE *fp;
int position;
clrscr();
fp = fopen ("file.txt", "r");
position = ftell(fp);
printf("Cursor position = %d\n",position);
fseek(fp,5,0);
position = ftell(fp);
printf("Cursor position = %d\n", position);
rewind(fp);
position = ftell(fp);
printf("Cursor position = %d", position);
fclose(fp);
getch();
return 0;
}
fseek( *file_pointer, numberOfCharacters, fromPosition ) –
This function is used to set the cursor position to the specific position. Using this function we
can set the cursor position from three different position they are as follows.
 from beginning of the file (indicated with 0)
 from current cursor position (indicated with 1)
 from ending of the file (indicated with 2)
Example Program to illustrate fseek() in C.
#include<stdio.h>
#include<conio.h>
int main(){
FILE *fp;
int position;
clrscr();
fp = fopen ("file.txt", "r");
position = ftell(fp);
printf("Cursor position = %d\n",position);
fseek(fp,5,0);
position = ftell(fp);
printf("Cursor position = %d\n", position);
fseek(fp, -5, 2);
position = ftell(fp);
printf("Cursor position = %d", position);
fclose(fp);
getch();
return 0;
}
Error Handling in C
C programming language does not support error handling that are occured at program
execution time. However, C provides a header file called error.h. The header file error.h
contains few methods and variables that are used to locate error occured during the program
execution. Generally, c programming function returns NULL or -1 in case of any error
occured, and there is a global variable called errno which stores the error code or error
number. The following table lists few errno values and thier meaning.

Error Number Meaning

1 Specified operation not permitted

2 No such file or directory.

3 No such process.

4 Interrupted system call.

5 IO Error

6 No such device or address

7 Argument list too long

8 Exec format error

9 Bad file number

10 No child processes

11 Try again

12 Out of memory

13 Permission denied

C programming language provides the following two methods to represent errors occured
during program execution.
 perror( )
 strerror( )
perror( ) - The perror() function returns a string passed to it along with the textual
representation of current errno value.
strerror( ) - The strerror() function returns a pointer to the string representation of the current
errno value. This method is defined in the header file string.h
Consider the following example program...
Example Program to illustrate error handling in C.
#include<stdio.h>
#include<conio.h>
int main(){
FILE *f_ptr;
f_ptr = fopen("abc.txt", "r");
if(f_ptr == NULL)
{
printf("Value of errno: %d\n ", errno);
printf("The error message is : %s\n", strerror(errno));
perror("Message from perror");
}
else {
printf("File is opened in reading mode!");
fclose(f_ptr);
}
return 0;
}
Programs on files:

C program to copy the contents of one file to another file?


#include <stdio.h>
#include <stdlib.h>
int main() {
char ch;
FILE *fp1, *fp2;
fp1 = fopen("file1.txt, "r");
fp2= fopen("file2.txt, "w");
if (fp1 == NULL)
{
printf("Press any key to exit...");
exit(EXIT_FAILURE);
}
else
{
while ((ch = fgetc(fp1)) != EOF)
fputc(ch, fp2);
}
fclose(fp2);

fp2= fopen("file2.txt, "r");


if (target == NULL)
{
fclose(fp2);
printf("Press any key to exit...");
exit(EXIT_FAILURE);
}
else
{
while ((ch = fgetc(fp2)) != EOF)
printf("%c",ch);
}
fclose(fp1);
fclose(fp2);
}

Merge contents of two files into a third file using C


#include <stdio.h>
#include <stdlib.h>
int main() {
char ch;
FILE *fp1, *fp2, *fp3;
fp1 = fopen("file1.txt, "r");
fp2 = fopen("file2.txt, "r");
fp3= fopen("file3.txt, "w");
if (fp1 == NULL)
{
printf("Press any key to exit...");
exit(EXIT_FAILURE);
}
else
{
while ((ch = fgetc(fp1)) != EOF)
fputc(ch, fp3);
}
if (fp2 == NULL)
{
printf("Press any key to exit...");
exit(EXIT_FAILURE);
}

else
{
while ((ch = fgetc(fp2)) != EOF)
fputc(ch,fp3);
}
fclose(fp3);

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


if (target == NULL)
{
fclose(fp3);
printf("Press any key to exit...");
exit(EXIT_FAILURE);
}
else
{
while ((ch = fgetc(fp3)) != EOF)
printf("%c",ch);
}
fclose(fp1);
fclose(fp2);
fclose(fp3);
}

You might also like