0% found this document useful (0 votes)
10 views31 pages

Background: Problems

The document discusses file management in programming, highlighting issues such as data loss upon program termination and the need for persistent storage. It covers file operations including opening, closing, reading, and writing files, as well as different file modes and functions in C programming. Additionally, it provides examples of programs for file creation, data manipulation, and structure handling in files.
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)
10 views31 pages

Background: Problems

The document discusses file management in programming, highlighting issues such as data loss upon program termination and the need for persistent storage. It covers file operations including opening, closing, reading, and writing files, as well as different file modes and functions in C programming. Additionally, it provides examples of programs for file creation, data manipulation, and structure handling in files.
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/ 31

Background

• Problems
• Whole data is lost once the program is terminated
• No persistent storage
• When volume of data is large it takes a lot of time to enter
the data again
• Wrongly type/entered data cannot be corrected easily
Concept of files
• File: Place on the disk where data can be stored for
later usage and alter that information whenever
necessary.
Classification of files
• Disk I/O Functions
• High Level
• Text
• Formatted
• Unformatted
• Binary
• Formatted
• Unformatted

• Low Level
Some important Functions:
• fopen(): creates a new file/Open existing file
• fclose(): closes a file which was opened for use
• fgetc(): read a character from a file
• fputc(): write a character to a file
• fprintf(): write a set of data values to a file
• fscanf(): reads a set of data values from a file
• fseek(): sets a position to a desired point in file
• ftell(): tells about the current position in the file
Opening a file
FILE *fp;
fp=fopen(“filename”,”mode”);

Here, the first statement declares the variable fp as a


“pointer to the data type FILE”.
The second statement opens the file named filename
with the purpose mode and the beginning address of the
buffer allocated for the file.
File Modes
• “r”: read mode
• “w”: write mode
• “a”: append mode
• “r+”: read and write mode
• “w+”: write and read mode
• “a+”: append and read mode
Closing a file
• The closing of file ensures that all the information with
the file is flushed out from the buffers and all links to
the file are broken.
• The file is closed using library function fclose() as:
fp.close()
String Input and output functions
• For reading a string value with spaces, we can use either
gets() or fgets() in C programming language. Here, we will
see what is the difference between gets() and fgets().
fgets(): is used to read string from file.
Syntax: fgets(string, int_value, fp);
• It reads a line from the specified stream and stores it into
the string pointed to by str. It stops when either n
characters are read, the newline character is read, or the
end-of-file is reached, whichever comes first.

• Here, int_value denotes the no. of characters in the string.


fputs(): is used to write string to file.
Syntax: fputs(string, fp);
#program to create a file and writing text into it
#include<stdio.h>
#include<stdlib.h>
void main()
{
FILE *fp;
system(“cls”);
fp=fopen("test.txt", "w");
if(fp==NULL)
{
printf("\n Cannot create file.");
exit(0);
}
else
{
printf("\n File is created.");
}
fputs("I study in DTU", fp);
fclose(fp);
getch();
}
Program to append text in the file
#include<stdio.h>
#include<stdlib.h>
void main()
{
FILE *fp;
clrscr();
fp=fopen("test.txt", "a");
if(fp==NULL)
{
printf("\n Cannot open file.");
exit(1);
}
else
{
printf("\n File is opened.");
}
fputs(“Delhi", fp);
fclose(fp);
getch();
}
Program to read the file char by char
void main()
{
FILE *fp;
char filename[20];
char c;
clrscr();
printf("Enter filename:\t");
gets(filename);
fp=fopen(filename, "r");
if(fp==NULL)
{
printf("\n Cannot open file.");
exit();
}
printf("\n The content of file is:\n");
while((c=fgetc(fp))!=EOF)
putchar(c);
fclose(fp);
getch();
}
END-OF-FILE (EOF)
• EOF is a special character (an integer with ASCII value
26) that indicates that the end-of-file has been reached.
This character can be generated from the keyboard by
typing Ctrl+Z.
• Defined in <stdio.h>
• When we are creating a file, the special character EOF,
is inserted after the last character of the file by the
Operating System.
File Copying
void main() exit();
{ }
FILE *sfp,*dfp; dfp=fopen(dfilename, "w");
char sfilename[20],dfilename[20]; if(dfp==NULL)
char c; {
clrscr(); printf("\n Destination file cannot
printf("Enter source filename:\t"); be created or opened.");
gets(sfilename); exit();
printf("\n Enter destination }
filename:\t"); while((c=fgetc(sfp))!=EOF)
gets(dfilename); fputc(c, dfp);
sfp=fopen(sfilename,"r"); printf("\n Copied........");
if(sfp==NULL) fclose(dfp);
{ fclose(sfp);
printf("\nSource file can't be getch();
opened."); }
Question
• Given a text file, create another text file deleting
all the vowels (a, e, i, o, u).
void main() printf("Cannot create file");
{ exit();
FILE *fp,*fpp; }
char c; while((c=fgetc(fp))!=EOF)
fp=fopen("C:\\test.txt","r+"); {
clrscr(); if((c!='a')&&(c!='e')&&(c!='i')
if(fp==NULL) &&(
{ c!='o')&&(c!='u'))
printf("Cannot open file"); fputc(c, fpp);
exit(); }
} fclose(fp);
fpp=fopen("C:\\hello.txt","w") fclose(fpp);
; getch();
if(fpp==NULL) }
{
• Define a structure for Vehicle Owner having data
members name, address, telephone number,
vehicle number and license number. Take the
data for ten owners, write them in file “Own.txt”.
Read the data from the file and display them.
struct vehicle_owner
{
char name[20];
char address[20];
long int phone_no;
int vehicle_no;
int license_no;
};
void main()
{
FILE *fp;
struct vehicle_owner vehicle[10], v[10];
int i;
clrscr();
fp=fopen("C:\\Own.txt","w");
if(fp==NULL)
{
printf("\nCannot create file.");
exit();
}
for(i=0;i<10;i++)
{
fflush(stdin);
printf("\n Enter information about vehicle owner %d",i+1);
printf("\n Enter name :\t");
gets(vehicle[i].name);
printf("\n Enter address:\t");
gets(vehicle[i].address);
printf("\n Enter telephone no:\t");
scanf("%ld", &vehicle[i].phone_no);
printf("\n Enter vehicle no:\t");
scanf("%d", &vehicle[i].vehicle_no);
printf("\n Enter license no:\t");
scanf("%d", &vehicle[i].license_no);
fprintf(fp,"%s\t%s\t%ld\t%d\t%d\n", vehicle[i].name, vehicle[i].address,
vehicle[i].phone_no, vehicle[i].vehicle_no, vehicle[i].license_no);
}
fclose(fp);
fp=fopen("C:\\Own.txt","r");
for(i=0;i<10;i++)
{
fscanf(fp,"%s %s %ld %d
%d",&v[i].name,&v[i].address,&v[i].phone_no,&v[i].vehicle_no,&v[i].lic
ense_
no);
printf("%s\t%s\t%ld\t%d\t%d\n",v[i].name,v[i].address,v[i].phone_no
,v[i].vehicl
e_no,v[i].license_no);
}
fclose(fp);
getch();
}
• Create a program to create a data file and write
the integers from 1 to 20 to this file and then read
the numbers from the file to display the squares
of the stored numbers.
#include <stdio.h> fprintf(fp,"%d\t",i);
void main() }
{ fclose(fp);
FILE *fp; fp=fopen("data.txt","r");
int i; printf("\nThe squares of the stored
int filedata; numbers are:\t");
fp=fopen("data.txt","w"); for(i=1;i<21;i++)
if(fp==NULL) {
{ fscanf(fp,"%d",&filedata);
printf("\nCannot create data file."); filedata=filedata*filedata;
exit(0); printf("%d\t", filedata);
} }
for(i=1;i<21;i++) getch();
{ }
Binary Data Files
The binary files organize data into blocks containing
contiguous bytes of information.
In binary file, the opening mode of text file is appended by a
character b i.e.
i. “r” is replaced by “rb”
ii. “w” is replaced by “wb”
iii. “a” is replaced by “ab”
iv. “r+” is replaced by “r+b”
v. “w+” is replaced by “w+b”
vi. “a+” is replaced by “a+b”
void main()
{
FILE *fp;
char c;
clrscr();
fp=fopen("C:\\test.dat","w+b");
if(fp==NULL)
{
printf("\nCannot create file.");
exit();
}
fputs("I study in DTU B.tech", fp);
fclose(fp);
getch();
}
/*Count no. of characters, spaces, and newlines in a file*/
#include <stdio.h>
void main() if(c==' ')
{ nos++;
FILE *fp; else if(c=='\n')
char text[100]; nol++;
char c; else
int noc=0,nos=0,nol=0; noc++;
fp=fopen("test.txt", "r"); }
if(fp==NULL) fclose(fp);
{ printf("\n No. of characters:%d",
printf("\nCannot create or open"); noc);
printf("\n No. of spaces:%d", nos);
exit(0); printf("\n No. of lines:%d", nol);
} getch();
while(1) }
{
c=fgetc(fp);
if(c==EOF)
break;
Read/Write array of structure to a binary mode file
#include <stdio.h> scanf("%s %d %f",e[i].name,&e[i].age,&temp);
void main() e[i].salary=temp;
{ fflush(stdin);
FILE *fp; }
struct emp fwrite(&e,sizeof(e),2,fp);
{ fclose(fp);
char name[40]; fp=fopen("emp.dat","rb");
int age; if(fp==NULL)
float salary; {
}; puts("Cannot open file");
struct emp e[2],ee[2]; exit(0);
int i; }
float temp; fread(&ee,sizeof(ee),2,fp);
fp=fopen("emp.dat","wb"); for(i=0;i<2;i++)
if(fp==NULL) printf("\n%s\t%d\t%.2f", ee[i].name, ee[i].age,
{ ee[i].salary);
puts("Cannot create or open file"); fclose(fp);
exit(0); getch();
} }
for(i=0;i<2;i++)
{
printf("\nEnter name, age and basic salary:");
Use of rewind function
#include <stdio.h> }
rewind(fp);
int main () { printf("\nrewind");
char str[] = "Welcome to DTU Delhi"; fseek(fp,20,SEEK_SET);
FILE *fp; printf("\n");
int ch; while(1) {
fp = fopen( "file.txt" , "w" ); ch = fgetc(fp);
fwrite(str, 1 , sizeof(str), fp ); if(ch==EOF ) {
fputs("\nI study in B.tech CS",fp); break ;
fclose(fp); }
fp = fopen( "file.txt" , "r" ); printf("%c", ch);
while(1) { }
ch = fgetc(fp); fclose(fp);
if(ch==EOF ) {
break ; return(0);
} }
printf("%c", ch);
Problem
A book record consists of its title, author, pages and
price. Write a program to perform following
operations:
– Read the records of 13 books
– Create at least one structure pointer to display the
records of 13 books
– Store records of all 13 books in the file “book.dat”
– Read only the information of 9 books from
“booklist.dat” skipping 2 books from first and 2 books
from last and display in terminal
#include <stdio.h> struct book bb[SIZE];
for(i=0;i<SIZE;i++)
#define SIZE 5
void main() {
{ printf("\nEnter record of
book%d",i+1);
struct book printf("\nEnter title:\t");
{ scanf("%s",b[i].title);
char title[40]; fflush(stdin);
char author[20]; printf("\nEnter author:\t");
int pages; scanf("%s",b[i].author);
float price; printf("\nEnter no. of pages:\t");
}; scanf("%d",&b[i].pages);
struct book b[SIZE]; printf("\nEnter price:\t");
int i; scanf("%f",&temp);
float temp; b[i].price=temp;
struct book *bp; }
FILE *fp;
bp=b; //bp=&b[0]; fseek(fp,sizeof(b)*2,0);
for(i=0;i<SIZE;i++) i=2;
{ printf("\nReading from file:");
printf("\nRecord of Book%d",i+1); while(fread(&bb,sizeof(bb),1,fp)==1)
printf("\nTitle:%s\tAuthor:%s",( bp+i)- {
>title,(bp+i)->author);
while(i<SIZE)
printf("\nNo. of
pages:%d\tPrice:%.2f\n",(bp+i)- {
>pages,(bp+i)->price); printf("\nTitle:%s\tAuthor:%s",bb[i].title,
} bb[i].author);
fp=fopen("book.dat","w+b"); printf("\nNo. Of
pages:%d\tPrice:%f\n",bb[i].pages,
if(fp==NULL) bb[i].price);
{ i++;
puts("Cannot create file"); }
exit(0); }
} fclose(fp);
for(i=0;i<SIZE;i++) getch();
fwrite(&b,sizeof(b),1,fp); }
rewind(fp);
References

• https://cse.iitkgp.ac.in/~bivasm/pds_notes/
• https://www.geeksforgeeks.org/
• https://overiq.com/c-programming-101/
• https://www.oreilly.com/library/
• https://www.cs.swarthmore.edu/~newhall/cs31/resources

You might also like