M5 C Notes
M5 C Notes
FILES
Many applications require information be to be read from or written to an auxiliary memory device. Such
information is stored on the memory device in the form of a data file. Thus, data files allow us to store the
information permanently, and to access and alter that information whenever necessary.
In C, an extensive set of library functions is available for creating and processing data files. Unlike other
Programming languages, C does not distinguish between sequential and direct access (random access)
data Files. However, there are two different types of data files, called stream-oriented or standard data
files, and system-oriented or low-level data files. Stream-oriented data files are easier to work with and are
more commonly used. Stream-oriented data files are subdivided into text files and unformatted data files.
Text files that are Sequential files consist of consecutive characters that are interpreted as individual data
items using scanf and printf functions where as unformatted data files, organizes data into blocks which
contains contiguous bytes of information involving complex data structures, like arrays and structures.
The library function fopen is used to open a file which is written as,
ptvar = fopen(file-name, file-type);
where file-name and file- type are strings that represent the name of the data file and file-type denotes the
manner in which the data file will be utilized.
e.g fp=fopen(“data.txt”,”r”); // open the file data.txt in read mode
The fopen function returns a pointer to the beginning of the buffer area associated with the file.
A NULL value is returned if the file cannot be opened as, for example, when an existing data file cannot
be found.
Finally, a data file must be closed at the end of the program. This can be accomplished with the library
function fclose. The syntax is:
fclose (ptvar);
Table 12-1 File-Type Specifications
File-Type Meaning
“r” Open an existing file for reading only.
“w” Open a new file for writing only. If a file with the specified file-name currently exists, it
will be destroyed and a new file created in its place.
“a” Open an existing file for appending (i.e., for adding new information at the end of the file).
A new file will be created if the file with the specified file-name does not exist.
“r+” Open an existing file for both reading and writing.
“w+” Open a new file for both reading and writing. If a file with the specified file-name currently
exists, it will be destroyed and a new file created in its place.
“a+” Open an existing file for both reading and appending. A new file will be created if the file
with the specified file-name does not exist.
1
Compiled by Divya Christopher, Assistant Professor in CSE, LMCST
File manipulation
/* read a line of lowercase text and store in uppercase within a data file */
#include <stdio.h>
#include <ctype.h>
int main( )
{
FILE * fpt ; / * define a pointer to predefined structure type FILE */
char c;
/* open a new data file for writing only*/
fpt = fopen("sample.dat", "w");
/* read each character and write its uppercase equivalent to the data file */
do
{
putc(toupper(c = getchar()), fpt ) ;
while (c != „\n‟) ;
/ * close the data file */
fclose (fpt) ;
}
After the program has been executed, the data file sample. dat will contain an uppercase equivalent of the
line of text entered into the computer from the keyboard.
Each of these functions requires four arguments: a pointer to the data block, the size of the data block, the
number of data blocks being transferred, and the stream pointer.
Stream means reading and writing of data. Streams allow users to access files efficiently. A stream is a
file or physical device like keyboard, printer and monitor.
Figure below shows the input and output streams. The input stream brings data to the program and output
stream collects data from the program. In this way, Input stream extracts data from the file and transfers it
to the program while the output stream stores the data into the file provided by the program.
2
Compiled by Divya Christopher, Assistant Professor in CSE, LMCST
File manipulation
The FILE object uses all these devices. The FILE object contains all the information about stream like
current position, pointer to any buffer, EOF (end of file).
Other file functions are listed below:
Function Operation
fgetc() or getc() Reads a character from current pointer position and advances the pointer to next
character
fprintf() Writes all types of data values to the file
fscanf() Reads all types of data values from the file
fputc() or putc() Writes character one by one to file
gets() Reads string from file
puts() Writes string to file
putw() Writes an integer to the file
getw() Reads an integer from the file
fread() Reads structured data written by fwrite() function
fwrite() Writes block of structured data to the file
fseek() Sets the pointer position anywhere in the file
feof() Detects the End of File
ftell() Returns the current pointer position
rewind() Sets the record pointer at the beginning of the file
Opening File in Append mode E.g.
#include<stdio.h>
#include<process.h>
{ FILE *fp;
char c;
printf(“Contents of file before appending \n”);
fp=fopen(“data.txt”,”r”);
while(!feof(fp))
{
c=fgetc(fp);
printf(“%c”,c);
}
fp=fopen(“data.txt”,”a”);
if(fp==NULL)
{
printf(“File cannot be appended”);
3
Compiled by Divya Christopher, Assistant Professor in CSE, LMCST
File manipulation
exit(1);
}
printf(“Enter string to append”);
while(c!=‟.‟)
{
c=getche();
fputc(c,fp);
}
fclose(fp);
printf(“\n Contents of File after appending”);
fp=fopen(“data.txt”,”r”);
while(!feof(fp))
{
c=fgetc(fp);
printf(“%c”,c);
}
}
Contents of file before appending LMCST.
Enter string to append LOURDES MATHA COLLEGE OF SCIENCE AND TECHNOLOGY
Contents of File after appending LMCST. LOURDES MATHA COLLEGE OF SCIENCE AND
TECHNOLOGY
Create a text file and perform the following: a) write data to the file b) read the data in a given
file and display the file contents on console c) append new data and display on console.
Qn.) Write a C program to enter name and age to text file, use w+ file mode.
#include<stdio.h>
int main() {
FILE *fp;
char text[15];
int age,rollno;
float cgpa;
fp=fopen("Text.txt","w+");
printf("Enter Name and \t Age \n");
scanf("%s %d", text, &age);
fprintf(fp, "%s %d", text, age);
printf("Name \t Age \n");
fscanf(fp, "%s %d", text, &age);
printf("%s\t %d\n", text, age);
fp=fopen("Text.txt","a");
printf("Enter Roll no and CGPA \n");
scanf("%d %f", &rollno, &cgpa);
fprintf(fp, "%d %f", rollno, cgpa);
printf("Name \t Age \t Rollno \t CGPA\t\n ");
fscanf(fp, "%s %d %d %f", text, &age, &rollno , &cgpa);
printf("%s\t %d\t %d \t %f \n", text, age, rollno, cgpa);
fclose(fp);
}
Output
Enter Name and Age
Rini 18
4
Compiled by Divya Christopher, Assistant Professor in CSE, LMCST
File manipulation
Name Age
Rini 18
#include <stdio.h>
#include <stdlib.h> // For exit() function
int main() {
char c[1000];
FILE *fptr;
if ((fptr = fopen("program.txt", "r")) == NULL) {
printf("Error! opening file");
exit(1);
}
return 0;
}
Write a C program to count the no of lines, words, characters, spaces in a text file?
#include <stdio.h>
void main()
{
int line_cnt = 0, sp_cnt=0,ch_cnt=0,wrd_cnt=1;
FILE *fp;
char ch;
fp = fopen("txt1.txt", "r");
if(fp==NULL)
printf("\nError: file not found");
printf("\nFile Contents are:");
printf("\n-------------------\n");
ch = fgetc(fp);
while (ch != EOF)
{
printf("%c",ch);
5
Compiled by Divya Christopher, Assistant Professor in CSE, LMCST
File manipulation
/* read a line of lowercase text and store in uppercase within a data file */
#include <stdio.h>
#include <ctype.h>
int main( )
{
FILE * fpt ; / * define a pointer to predefined structure type FILE */
char c;
/* open a new data file for writing only*/
fpt = fopen("sample.dat", "w");
/* read each character and write its uppercase equivalent to the data file */
do
{
putc(toupper(c = getchar()), fpt ) ;
while (c != „\n‟) ;
/ * close the data file */
fclose (fpt) ;
}
After the program has been executed, the data file sample. dat will contain an uppercase equivalent of the
line of text entered into the computer from the keyboard.
Each of these functions requires four arguments: a pointer to the data block, the size of the data block, the
number of data blocks being transferred, and the stream pointer.
Stream means reading and writing of data. Streams allow users to access files efficiently. A stream is a
file or physical device like keyboard, printer and monitor.
Figure below shows the input and output streams. The input stream brings data to the program and output
stream collects data from the program. In this way, Input stream extracts data from the file and transfers it
to the program while the output stream stores the data into the file provided by the program.
2
Compiled by Divya Christopher, Assistant Professor in CSE, LMCST
File manipulation
The FILE object uses all these devices. The FILE object contains all the information about stream like
current position, pointer to any buffer, EOF (end of file).
Other file functions are listed below:
Function Operation
fgetc() or getc() Reads a character from current pointer position and advances the pointer to next
character
fprintf() Writes all types of data values to the file
fscanf() Reads all types of data values from the file
fputc() or putc() Writes character one by one to file
gets() Reads string from file
puts() Writes string to file
putw() Writes an integer to the file
getw() Reads an integer from the file
fread() Reads structured data written by fwrite() function
fwrite() Writes block of structured data to the file
fseek() Sets the pointer position anywhere in the file
feof() Detects the End of File
ftell() Returns the current pointer position
rewind() Sets the record pointer at the beginning of the file
Opening File in Append mode E.g.
#include<stdio.h>
#include<process.h>
{ FILE *fp;
char c;
printf(“Contents of file before appending \n”);
fp=fopen(“data.txt”,”r”);
while(!feof(fp))
{
c=fgetc(fp);
printf(“%c”,c);
}
fp=fopen(“data.txt”,”a”);
if(fp==NULL)
{
printf(“File cannot be appended”);
3
Compiled by Divya Christopher, Assistant Professor in CSE, LMCST
File manipulation
exit(1);
}
if(fwrite != 0)
printf("contents to file written successfully !\n");
else
printf("error writing file !\n");
// close file
fclose (outfile);
}
// C program for reading a block of data involving structure from a file
#include <stdio.h>
#include <stdlib.h>
// close file
fclose (infile);
}
gcc demoread.c
./a.out
id = 1 name = royce anto
id = 2 name = rinil jose
8
Compiled by Divya Christopher, Assistant Professor in CSE, LMCST
File manipulation
Write a program to write and read the information about player containing players name, age and runs.
Use fread( ) and fwrite( ) functions?
#include<stdio.h>
#include<process.h>
struct record
{
int age;
int runs;
};
void main()
{
FILE *fp;
struct record emp;
fp=fopen(“record.dat”,”w”);
if(fp==NULL)
{
printf(“Cannot open file”);
exit(1);
}
printf(“Enter player name, age and runs scored”);
printf(“==============================”);
scanf(“%s %d %d”,emp.player, &emp.age,&emp.runs);
fwrite(&emp,sizeof(emp),1,fp);
fclose(fp);
if(fp=fopen(“record.dat”,”r”))==NULL)
{
printf(“error in opening file”);
exit(1);
}
printf(\n Record entered is\n”);
fread(&emp,sizeof(emp),1,fp);
printf(“%s %d %d”,emp.player, emp.age, emp.runs);
fclose(fp);
}
OUTPUT
Enter player name, age and runs scored
=============================
Arun 25 10000
Record entered is
Arun 25 10000
fseek() function
It is a file function used to position file pointer on the stream. Three arguments are passed through this
function:
File pointer
Negative or Positive number used to re-position file pointer towards backward or forward
direction.
The current position of the file pointer
9
Compiled by Divya Christopher, Assistant Professor in CSE, LMCST
File manipulation
}
Output
gcc pgm.c
$ ./a.out
Enter name of first file a.txt
Enter name of second file b.txt
Enter name to store merged file merge.txt
Two files merged merge.txt successfully.
fwrite() function
The fwrite() function is used to write records (sequence of bytes) to the file. A record may be an array or a
structure. The Syntax of fwrite() function is as shown below:
fwrite( ptr, int size, int n, FILE *fp );
The fwrite() function takes four arguments.
ptr : ptr is the reference of an array or a structure stored in memory.
size : size is the total number of bytes to be written.
n : n is number of times a record will be written.
FILE* : FILE* is a file where the records will be written in binary mode.
The fread() function is used to read bytes form the file.
struct person
{
int id;
char fname[20];
char lname[20];
};
int main ()
{
FILE *outfile;
7
Compiled by Divya Christopher, Assistant Professor in CSE, LMCST
File manipulation
exit(1);
}
if(fwrite != 0)
printf("contents to file written successfully !\n");
else
printf("error writing file !\n");
// close file
fclose (outfile);
}
// C program for reading a block of data involving structure from a file
#include <stdio.h>
#include <stdlib.h>
// close file
fclose (infile);
}
gcc demoread.c
./a.out
id = 1 name = royce anto
id = 2 name = rinil jose
8
Compiled by Divya Christopher, Assistant Professor in CSE, LMCST
File manipulation
Write a program to write and read the information about player containing players name, age and runs.
Use fread( ) and fwrite( ) functions?
#include<stdio.h>
#include<process.h>
struct record
{
int age;
int runs;
};
void main()
{
FILE *fp;
struct record emp;
fp=fopen(“record.dat”,”w”);
if(fp==NULL)
{
printf(“Cannot open file”);
exit(1);
}
printf(“Enter player name, age and runs scored”);
printf(“==============================”);
scanf(“%s %d %d”,emp.player, &emp.age,&emp.runs);
fwrite(&emp,sizeof(emp),1,fp);
fclose(fp);
if(fp=fopen(“record.dat”,”r”))==NULL)
{
printf(“error in opening file”);
exit(1);
}
printf(\n Record entered is\n”);
fread(&emp,sizeof(emp),1,fp);
printf(“%s %d %d”,emp.player, emp.age, emp.runs);
fclose(fp);
}
OUTPUT
Enter player name, age and runs scored
=============================
Arun 25 10000
Record entered is
Arun 25 10000
fseek() function
It is a file function used to position file pointer on the stream. Three arguments are passed through this
function:
File pointer
Negative or Positive number used to re-position file pointer towards backward or forward
direction.
The current position of the file pointer
9
Compiled by Divya Christopher, Assistant Professor in CSE, LMCST
File manipulation
int main()
{
FILE *fptr1, *fptr2;
char filename[100], c;
fclose(fptr1);
fclose(fptr2);
return 0;
}
Output:
Enter the filename to open for reading
a.txt
Enter the filename to open for writing
b.txt
HELLO WORLD
Contents copied to b.txt
13
Compiled by Divya Christopher, Assistant Professor in CSE, LMCST