Professional Documents
Culture Documents
Files C
Files C
In C programming, file is a place on disk where a group of related data is stored.A set of records on the
disk is called as a file. Data is kept as a stream of characters in a file.
C provides a number of functions that helps to perform basic file operations. Following are the
functions,
Function Description
1. fopen() create a new file or open a existing file
2. fclose() closes a file
3. getc() reads a character from a file
4. putc() writes a character to a file
5. fscanf() reads a set of data from a file
6. fprintf() writes a set of data to a file
7. getw() reads a integer from a file
8. putw() writes a integer to a file
9. fseek() set the position to desire point
10. ftell() gives current position in the file
11. rewind() set the position to the begining point
FILE *ptr;
File Operations
Opening a file
Opening a file is performed using library function fopen(). The syntax for opening a file in standard I/O is:
Closing a File
The file should be closed after reading/writing of a file. Closing a file is performed using library function
fclose( ).
NOTE : When a file is closed automatically, the EOF character is added as the last character of the file. Thus
for any text file , the last character is EOF character. EOF character can be supplied (entered) from the keyboard
by pressing ‘Ctrl’ and ‘z’ keys simultaneously.
- Write a program to create and write data in a file and read the data from that file. (or) Write a program in C
to create a file and write some text data in that file and read the data from that file and display the contents of
the file on the user screen.
#include <stdio.h>
main( )
{
char ch;
FILE *fptr;
clrscr();
printf("\n Enter contents for the file\n");
fptr = fopen("data.txt", "w"); /* Opening the file in write mode */
while( (ch=getchar( )) != '$') /* getchar( ) is for reading one character from the keyboard */
{
putc(ch, fptr); /* Writing one character in the file using putc( ) */
}
fclose(fptr);
fptr=fopen("data.txt", "r"); /* Opening the file for reading */
while( (ch=getc(fptr)) != EOF) /* Reading one character from the file using getc( ) */
{
printf("%c", ch); /* character taken from the file is assigned to ‘ch’ and printed on user screen */
}
fclose(fptr);
getch();
}
INPUT/OUTPUT : Enter contents for the file
Welcome to files concept.$
Welcome to files concept.
NOTE : putc( ) or fputc( ) can be used for writing characters. getc( ) or fgetc( ) can be used for reading
characters.
We can give any name as file name. .txt means it is a text file.
-Write a program in C that converts the contents of a file into capital letters and copy the contents in another
file. (This is also a C program to copy the contents of one file to another).
#include<stdio.h>
#include<ctype.h>
main( )
{
char ch;
FILE *p1, *p2;
clrscr();
printf("\n Enter data for the file \n\n");
p1=fopen("afile.txt", "w");
while( (ch=getchar( )) != '$')
{
putc(ch, p1);
}
fclose(p1);
p1=fopen("afile.txt", "r");
p2=fopen("bfile.txt", "w");
while( (ch=getc(p1)) != EOF )
{
putc(toupper(ch), p2); /* toupper( ) converts a small case alphabet to upper case */
} /* After conversion, the uppercase alphabet is written(copied) in ‘bfile’ */
fclose(p1);
fclose(p2);
printf("\n Contents of upper case file \n");
p2=fopen("bfile.txt", "r");
while( (ch=getc(p2)) != EOF)
printf("%c", ch);
fclose(p2);
getch();
}
INPUT/OUTPUT : Enter data for the file
Good Morning. Ready 123 start$
Contents of upper case file
GOOD MORNING. READY 123 START
NOTE : In the above program we are copying the contents of ‘afile’ to ‘bfile’. Before copying we are converting all the
lower case alphabets into upper case.
NOTE : toupper( ) function is in ctype.h header file. It converts only lower case alphabets into uppercase. It
does nothing for other characters. Similarly tolower( ) function converts upper case alphabets to
lower case.
-Write a program to split a Main_file into two files, say file1 and file2. Read lines into the Main_file from standard
input. File1 should consist of odd numbered lines and file2 should consist of even numbered lines.
#include<stdio.h>
main()
{
int num=1;
char ch;
FILE *p,*p1,*p2;
clrscr();
printf("\n Enter few lines of data for main file \n\n");
p=fopen("mainfile.txt", "w");
while( (ch=getchar( )) != ‘$’ ) /* At the end input ‘$’ symbol (here we can use any symbol to stop) */
{
putc(ch, p);
}
fclose(p);
p=fopen("mainfile.txt", "r");
p1=fopen("file1.txt", "w");
p2=fopen("file2.txt", "w");
while( (ch=getc(p)) != EOF )
{
if(ch=='\n')
num++;
if(num%2!=0)
putc(ch, p1); /* Copy the odd numbered lines in the file-1 */
else
putc(ch, p2); /* Copy the even numbered lines in file-2 */
}
fclose(p);
fclose(p1);
fclose(p2);
printf("\n Contents of File-1 \n");
p1=fopen("file1.txt", "r");
while( (ch=getc(p1)) != EOF )
printf("%c", ch);
fclose(p1);
printf("\n Contents of File-2 \n");
p2=fopen("file2.txt", "r");
while( (ch=getc(p2)) != EOF )
printf("%c", ch);
fclose(p2);
getch();
}
- Write a program to merge(append) two files. Append first file contents to the second file.
#include<stdio.h>
main( )
{
char ch;
FILE *p1,*p2;
clrscr( );
printf("\n Enter the data for first file \n\n");
p1=fopen("one.txt", "w");
while( (ch=getchar( )) != '$')
putc(ch, p1);
fclose(p1);
printf("\n Enter data for second file \n");
p2=fopen("two.txt", "w");
while( (ch=getchar( )) != '$')
putc(ch, p2);
fclose(p2);
p1=fopen("one.txt", "r");
p2=fopen("two.txt", "a");
while( (ch=getc(p1)) != EOF )
putc(ch, p2); /* Append the contents of first file to second file */
fclose(p1);
fclose(p2);
printf("\n After Merging (appending)
Contents of Second File \n");
p2=fopen("two.txt", "r");
while( (ch=getc(p2)) != EOF )
printf("%c", ch);
fclose(p2);
getch( );
}
INPUT/OUTPUT :
Syntax :
putw(int w, FILE *fptr);
Eg. int x;
FILE *fptr;
putw(x, fptr);
Syntax : getw(fptr);
-Write a program to read and print text file of integers. (or) Write a C program to create a file and write some
integers in that file and then read those integers from that file and display on the user screen.
#include <stdio.h>
main( )
{
int n, i, x;
FILE *p;
clrscr();
printf("\n Enter number of integers u want to put in the file : ");
scanf("%d", &n);
p = fopen("intfile.txt", "w"); /* Opening the file in write mode */
printf("\n Enter %d integers for the file \n", n);
for(i=0; i<n ; i++)
{
scanf("%d", &x); /* Take one integer from key board */
putw(x, p); /* Writing one integer in the file using putw( ) */
}
fclose(p);
printf(“\n Contents of the file \n”);
p = fopen("intfile.txt", "r"); /* Opening the file for reading */
while( (x=getw(p)) != EOF) /* Reading one integer from the file using getw( ) */
{
printf("%d \t",x);
}
fclose(p);
getch();
}
INPUT/OUTPUT : Enter number of integers u want to put in the file : 6
Enter 6 integers for the file
45 7 88 23 -12 25
Contents of the file
45 7 88 23 -12 25
NOTE : Even in this file "intfile.txt", last character is EOF character. After reading the last integer, if we try to
read next integer we will get EOF character. Like that condition in while loop becomes false.
- Write a program in C that reads the contents of a file containing integers and displays the largest among the
integers on the user screen.
#include <stdio.h>
main( )
{
int n, i, x, max= -999;
FILE *p;
clrscr();
printf("\n Enter number of integers u want to put in the file : ");
scanf("%d", &n);
p = fopen("intfile.txt","w"); /* Opening the file in write mode */
printf("\n Enter %d integers for the file \n", n);
for(i=0; i<n ; i++)
{
scanf("%d", &x);
putw(x, p); /* Writing one integer in the file */
}
fclose(p);
p = fopen("intfile.txt","r"); /* Opening the file for reading */
while( (x=getw(p)) != EOF) /* Reading one integer from the file */
{
if(x > max)
max=x;
}
fclose(p);
printf("\n Biggest integer in the file = %d", max);
getch();
}
Syntax : fgets( String variable, Max length of string variable, FILE *fptr );
NOTE : while( strlen(gets(s)) > 0) : When we give a NULL string (i.e Pressing ‘Enter key’ ) while condition
becomes false since length of the NULL string is 0.
while( fgets(s, 20, fp) != NULL) : Reads one string from the file each time to the variable ‘s’. The last
string is NULL string. When reads this NULL string condition becomes false.
fprintf( ) : By using this function, different types of data in the required format (i.e spaces etc.) can be
stored(writing) in the file at a time.
fscanf( ) : By using this function, different types of data from the file is read.
So far, we have accessed the contents of the file in the sequential manner(if we want to read directly the
5 character in a file, it is not possible. First read 1st character, then 2nd , then 4th and the 5th character).
th
In C language we can access the file contents in random order also. If we want to read directly the 5th
character, then move the file pointer to the 5th position and read that character.
1. ftell( )
2. rewind( )
3. fseek( )
1. ftell( ) : tells (returns) the current position of the control in the file. At what position we are now in the
file.
2. rewind( ) : Resets the file position indicator to the beginning of the file. i.e control comes to the first
position of the file.
Eg. rewind(fptr);
3. fseek( ) : Sets the file position indicator to the required position of the file.
(1) offset – Specifies the number of positions(bytes) to be moved from the whence. If the offset value
is +ve then move forward. If the offset value is -ve then move backwards.
C R E C I S I N T P T EOF
File position: 0 1 3 4 5 6 7 8 9 10 11 12 13 14 15
↑
C R E C I S I N T P T EOF
File position: 0 1 3 4 5 6 7 8 9 10 11 12 13 14 15
↑
-Write a program in C that reverses the contents of a file and copies it into a new file. (or)
Write a program to display the contents of the file in reverse after copying in another file.
#include <stdio.h>
main( )
{
char ch;
int chars=0; /* ‘chars’ is for counting total no. of characters in the file */
long int i;
FILE *p1,*p2;
clrscr();
printf("\n Enter contents for data file\n");
p1=fopen("data.txt", "w");
while( (ch=getchar( )) != '$')
{
putc(ch, p1);
chars++;
}
fclose(p1);
p1=fopen("data.txt", "r");
p2=fopen("reverse.txt", "w");
for(i=1;i<=chars; i++)
{
fseek(p1, -i, 2); /* As offset is long int, 'i' is declared as long int */
ch=getc(p1); /* Take(Read) the character from file ‘data.txt’ */
putc(ch,p2); /* Write this character in the file ‘reverse.txt’ */
}
fclose(p1);
fclose(p2);
printf("\n Contents of Reverse file\n");
p2=fopen("reverse.txt", "r");
while( (ch=getc(p2)) != EOF)
printf("%c",ch);
fclose(p2);
getch();
}
INPUT/OUTPUT : Enter contents for data file
CREC is in Tirupati.It was started in 2004.
Contents of Reverse file
.4002 ni detrats saw tI.itapuriT ni si CERC
NOTE : fseek(p1,-i,2); Come to end of the file. From there move backwards by ‘i’ number of positions.
NOTE : feof( ) function returns true if end of file is reached, otherwise returns false.
Syntax : feof(fptr);
Differences between Text File and Binary File
Depending upon the way file is opened for processing, a file is classified into text file and binary file.
Working of binary files is similar to text files with few differences in opening modes, reading from file and
writing to file.
(1) (i) Opening modes of Text Files are r, w, a, r+, w+, a+.
(ii) Opening modes of binary files are rb, rb+, wb, wb+,ab and ab+.
Functions fread() and fwrite() are used for reading from and writing to a file on the disk
respectively in case of binary files.
(i) In text mode, a newline character is converted into the carriage return-linefeed combination before
being written to the disk. Likewise, the carriage return-linefeed combination on the disk is converted
back into a newline when the file is read by a C program.
(ii) If a file is opened in binary mode, as opposed to text mode, these conversions will not take place.
(i) In text mode, a special character, whose ASCII value is 26, is inserted after the last character in the
file to mark the end of file. If this character is detected at any point in the file, the read function
would return the EOF signal to the program.
(ii) There is no such special EOF character present in the binary mode files to mark the end of file. The
binary mode files keep track of the end of file from the number of character present in the directory
entry of the file.
(i) In text file the numbers are stored as strings of characters. Thus, for eg. the integer 31912, even
though it occupies 2 bytes in main memory, when transferred to the disk it would occupy 5 bytes,
one byte per character(it treats each digit as one character). Thus, storing large amount of number
data in a disk file using text mode may be inefficient.
(iii) In binary mode, the integer 31912 will occupy 2 Bytes in Main memory and also in the disk. This
mode uses the functions fread() and fwrite() to read and write in the file.
fwrite( ) :
To write records(structures) in a file fwrite( ) function is used. Here file has to be opened in binary
mode.
Syntax : fwrite(void *Buffer, int size, int Count, FILE *ptr); (or)
fwrite(&Structure variable name, sizeof(structure variable), Number of records we want to write,FILE *fptr);
fread( ) :
To Read records(structures) from a File using fread( ) function. Here file has to be opened in binary
mode. Returns no. of records read.
Syntax :
int fread(void *Buffer, int size, int Count, FILE *ptr); (or)
fread(&Structure variable name, sizeof(structure variable), Number of records we want to write,FILE *fptr);
- Write a C program to create a file and write some structures(records) in that file and then read those records
and and display on the user screen. (or) Write a C program to illustrate fwrite() and fread() functions. (or)
Write a C program that displays the attributes of a file which contains records (structures).
#include<stdio.h>
main()
{
struct student
{
int roll;
char name[25];
float marks;
};
FILE *fp;
char ch;
struct student s;
clrscr();
fp = fopen("student.dat","w");
do
{
printf("\nEnter Name,RollNo,Marks \n");
fflush(stdin);
gets(s.name);
scanf("%d%f",&s.roll,&s.marks);
fwrite(&s, sizeof(s),1, fp); /* Writing one record in a file */
printf("\nDo you want to add another data (y/n) : ");
fflush(stdin);
scanf("%c",&ch);
} while(ch=='y');
fclose(fp);
printf("\n\tRoll\tName\tMarks\n");
fp=fopen("student.dat","r");
while(fread(&s,sizeof(s),1,fp)>0)
printf("\n\t%s\t%d\t%f",s.name,s.roll,s.marks);
fclose(fp);
getch( );
}
INPUT/OUTPUT : Enter Name, RollNo, Marks
Rao
543
78
Do you want to add another data (y/n) : y
Enter Name, RollNo, Marks
Kumar
567
58
Do you want to add another data (y/n) : n
while(fread(&s, sizeof(s),1,fp) > 0) : In the above eg. , fread( ) brings one record from the file and
returns 1. Thus while condition is true. After reading two records, tries to read 3rd record. 3rd record is not
available. Hence the fread() function returns 0. Thus while condition becomes false.
-Write a program to read information about student records which contains name, RollNo, marks in 6 subjects
for n number of students. Write the data(records) of these students in a file. According to JNTUA rules, find the
class of each student find the class and write the result in the another file and display the result on the user
screen.
#include<stdio.h>
#include<string.h>
main()
{
struct student
{
int roll, marks[6];
char name[25], class[20];
};
FILE *p1,*p2;
int i, j, n, tot;
struct student s[60];
clrscr();
p1 = fopen("student.dat","wb");
printf("\n Enter number of students : ");
scanf("%d",&n);
for(i=0 ; i<n ; i++)
{
printf("\nEnter Name,RollNo,Marks in 6 subjects for student-%d\n",i+1);
fflush(stdin);
gets(s[i].name);
scanf("%d",&s[i].roll);
for(j=0;j<6;j++)
scanf("%d", &s[i].marks[j]);
fflush(stdin);
strcpy(s[i].class," ");
fwrite(&s[i],sizeof(struct student),1,p1);
}
fclose(p1);
p1=fopen("student.dat","r");
p2=fopen("results.dat","w");
for(i=0 ; i<n ; i++)
{
fread(&s[i],sizeof(struct student),1,p1);
printf("\n%s\t%d\t%d\t%d\t%d\t%d\t%d\t%d",s[i].name,s[i].roll,s[i].marks[0],s[i].marks[1],
s[i].marks[2],s[i].marks[3],s[i].marks[4],s[i].marks[5]);
for(j=0;j<6;j++)
{
if(s[i].marks[j] < 40)
{
strcpy(s[i].class,"FAIL");
fwrite(&s[i],sizeof(s[i]),1,p2);
break;
}
else
{
tot=0;
for(j=0 ; j<6 ; j++)
tot = tot + s[i].marks[j];
if(tot>=360)
strcpy(s[i].class,"FIRST CLASS");
else
if(tot>=300)
strcpy(s[i].class,"SECOND CLASS");
else
strcpy(s[i].class,"THIRD CLASS");
fwrite(&s[i],sizeof(s[i]),1,p2);
}
}
}
fclose(p1);
fclose(p2);
p2=fopen("results.dat","r");
printf("\n \tName\tRoll No. Class\n\n");
for(i=0 ; i<n ; i++)
{
if(fread(&s[i],sizeof(struct student),1,p2) > 0)
printf("\n\t%s\t%d\t%s",s[i].name,s[i].roll,s[i].class);
}
fclose(p2);
getch();
}
Preprocessors :
Preprocessor is a program that processes the source code(i.e C file) before it goes through compilation
process. The C Preprocessors are identified by the presence of hash symbol(#) at the beginning of the line.
There are 3 types of preprocessor statements i.e the C preprocessor provides 3 types of facilities.
The C preprocessor will replace the macros with their definitions throughout the program.
During thepreprocessing, the preprocessor replaces every occurrence of PI in the program with 3.142.
/* Example */
#include <stdio.h>
#define PI 3.142
main()
{
float a,p,r;
clrscr( );
printf("\n Enter the radius value : ");
scanf("%f",&r);
a=PI*r*r;
p=2*PI*r;
printf("\n Area = %f, Perimeter = %f", a,p);
getch();
}
INPUT/OUTPUT : Enter the radius value : 4.5
Area = 63.6255, Perimeter = 28.278
Using special preprocessing directives i.e #if, #elif, #else, #endif we can include or exclude parts of the
program according to various conditions.