Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 18

CS3101 PROGRAMMING FOR PROBLEM SOLVING USING C

UNIT V FILE PROCESSING AND GRAPHICS PROGRAMMING 9


Introduction to Files, Types of files: text file, binary file. File operations: open,
close, read, write, append. Sequential access file, Random access file, Introduction
to Graphics Programming in C basic concepts in graphics programming.

5.1 Introduction

A file is a semi-permanent, named collection of data. A File is usually


stored on magnetic media, such as a hard disk or magnetic tape. Semi-
permanent means that data saved in files stays safe until it is deleted or
modified.
Named means that a particular collection of data on a disk has a name,
like mydata.dat and access to the collection is done by using its name.
A file represents a sequence of bytes on the disk where a group of related
data is stored. File is created for permanent storage of data. It is a readymade
structure.

5.1.1 Types of Files

1. Text file

2. Binary file

1. Text Files

The user can create these files easily while handling files in C. It stores
information in the form of ASCII characters internally, and when the file is opened,
the content is readable by humans. It can be created by any text editor with a .txt
or .rtf (rich text) extension. Since text files are simple, they can be edited by any
text editor like Microsoft Word, Notepad, Apple Text Edit, etc.
2. Binary file

It stores information in the form of 0’s or 1’s, and it is saved with the .bin
extension, taking less space. Since it is stored in a binary number system
format, it is not readable by humans. Therefore, it is more secure than a text file.
5.2 File Operations
In C, you can perform four major operations on files, either text or binary:

1. Creating a new file


2. Opening an existing file
3. Closing a file
4. Reading from and writing information to a file

5.2.1 Creating a new file

FILE is basically a data type, and we need to create a pointer variable to work with
it (fptr). For now, this line is not important. It's just something you need when
working with files.

To actually open a file, use the fopen() function, which takes two parameters:

Paramete Description
r

filename The name of the actual file you want to open (or create),
like filename.txt

mode A single character, which represents what you want to do with


the file (read, write or append):
w - Writes to a file
a - Appends new data to a file
r - Reads from a file

5.2.2 Opening a file - for creation and edit


Opening a file is performed using the fopen() function defined in the stdio.h header
file.
The syntax for opening a file in standard I/O is:

ptr = fopen("fileopen","mode");

For example,

fopen("E:\\cprogram\\newprogram.txt","w");

fopen("E:\\cprogram\\oldprogram.bin","rb");
● Let's suppose the file newprogram.txt doesn't exist in the location E:\cprogram. The
first function creates a new file named newprogram.txt and opens it for writing as
per the mode 'w'.
The writing mode allows you to create and edit (overwrite) the contents of the file.
● Now let's suppose the second binary file oldprogram.bin exists in the location E:\
cprogram. The second function opens the existing file for reading in binary
mode 'rb'. The reading mode only allows you to read the file, you cannot write into
the file.

We can use one of the following modes in the fopen() function.

Mode Description

r opens a text file in read mode

w opens a text file in write mode

a opens a text file in append mode

r+ opens a text file in read and write mode

w+ opens a text file in read and write mode

a+ opens a text file in read and write mode

rb opens a binary file in read mode

wb opens a binary file in write mode

ab opens a binary file in append mode

rb+ opens a binary file in read and write mode

wb+ opens a binary file in read and write mode

ab+ opens a binary file in read and write mode


5.2.3. Closing a File
The file (both text and binary) should be closed after reading/writing.

Closing a file is performed using the fclose() function.


fclose(fptr);
Here, fptr is a file pointer associated with the file to be closed.
5.2.4 Reading and writing to a text file
For reading and writing to a text file, we use the functions fprintf() and fscanf().
They are just the file versions of printf() and scanf(). The only difference is
that fprintf() and fscanf() expects a pointer to the structure FILE.
Example 1: Write to a text file

#include <stdio.h>

#include <stdlib.h>

int main()

int num;

FILE *fptr;

fptr = fopen("C:\\program.txt","w");

if(fptr == NULL)

printf("Error!");

exit(1);

printf("Enter num: ");

scanf("%d",&num);

fprintf(fptr,"%d",num);

fclose(fptr);

return 0;

Example 2: Read from a text file

#include <stdio.h>
int main()

int num;

FILE *fptr;

if ((fptr = fopen("C:\\program.txt","r")) == NULL){

printf("Error! opening file");

// Program exits if the file pointer returns NULL.

exit(1);

fscanf(fptr,"%d", &num);

printf("Value of n=%d", num);

fclose(fptr);

return 0;

Reading and writing to a binary file


Functions fread() and fwrite() are used for reading from and writing to a file on the
disk respectively in case of binary files.
Writing to a binary file
To write into a binary file, you need to use the fwrite() function. The functions take
four arguments:
1. address of data to be written in the disk
2. size of data to be written in the disk
3. number of such type of data
4. pointer to the file where you want to write.

fwrite(addressData, sizeData, numbersData, pointerToFile);

Example 3: Write to a binary file using fwrite()

#include <stdio.h>

#include <stdlib.h>

struct threeNum

{ int n1, n2, n3;

};

int main(){

int n;

struct threeNum num;

FILE *fptr;

if ((fptr = fopen("C:\\program.bin","wb")) == NULL){

printf("Error! opening file");

// Program exits if the file pointer returns NULL.

exit(1);
}

for(n = 1; n < 5; ++n)

num.n1 = n;

num.n2 = 5*n;

num.n3 = 5*n + 1;

fwrite(&num, sizeof(struct threeNum), 1, fptr);

fclose(fptr);

return 0;

Reading from a binary file


Function fread() also take 4 arguments similar to the fwrite() function as above.
fread(addressData, sizeData, numbersData, pointerToFile);

Example 4: Read from a binary file using fread()

#include <stdio.h>

#include <stdlib.h>

struct threeNum{

int n1, n2, n3;

};

int main(){

int n;
struct threeNum num;

FILE *fptr;

if ((fptr = fopen("C:\\program.bin","rb")) == NULL){

printf("Error! opening file");

// Program exits if the file pointer returns NULL.

exit(1);

for(n = 1; n < 5; ++n)

fread(&num, sizeof(struct threeNum), 1, fptr);

printf("n1: %d\tn2: %d\tn3: %d\n", num.n1, num.n2, num.n3);

fclose(fptr);

return 0;

Getting data using fseek()


If you have many records inside a file and need to access a record at a specific
position, you need to loop through all the records before it to get the record.

This will waste a lot of memory and operation time. An easier way to get to the
required data can be achieved using fseek().
As the name suggests, fseek() seeks the cursor to the given record in the file.
Syntax of fseek()

fseek(FILE * stream, long int offset, int whence);


The first parameter stream is the pointer to the file. The second parameter is the
position of the record to be found, and the third parameter specifies the location
where the offset starts.

Different whence in fseek()

Whence Meaning

SEEK_SET Starts the offset from the beginning of the file.

SEEK_END Starts the offset from the end of the file.

Starts the offset from the current location of the cursor in


SEEK_CUR
the file.

Example 5: fseek()

#include <stdio.h>

#include <stdlib.h>

struct threeNum

int n1, n2, n3;

};

int main()

int n;

struct threeNum num;

FILE *fptr;
if ((fptr = fopen("C:\\program.bin","rb")) == NULL){

printf("Error! opening file");

// Program exits if the file pointer returns NULL.

exit(1);

// Moves the cursor to the end of the file

fseek(fptr, -sizeof(struct threeNum), SEEK_END);

for(n = 1; n < 5; ++n)

fread(&num, sizeof(struct threeNum), 1, fptr);

printf("n1: %d\tn2: %d\tn3: %d\n", num.n1, num.n2, num.n3);

fseek(fptr, -2*sizeof(struct threeNum), SEEK_CUR);

fclose(fptr);

return 0;

5.3 SEQUENTIAL ACCESS FILE


The data items in a sequential access file are arranged one after another in a
sequence. Each data item can be accessed in the same order in which they have been
stored. It is only possible to read a sequential file from the beginning. To access a
particular data within the sequential access file, data has to be read one data at a
time, until the required data is reached.
Reading data from a sequential file can be done using the various C functions like
fscanf(), fgets(), fgetc(), fread(). Writing data to a sequential file can be done using
the various Cfunctions like fprintf(), fputs(), fputc(), fwrite().
EXAMPLE PROGRAM:
Finding average of numbers stored in sequential access file
#include <stdio.h>
#include <math.h>
// Read the numbers and return average
float average(FILE *input)
{
float term,sum;
int n;
sum = 0.0;
n = 0;
while(!feof(input))
{
fscanf(input,"%f",&term);
sum = sum + term;
n = n + 1;
}
return sum/n;
}
int main ()
{
FILE *input;
float avg;
input = fopen("data.txt","r");
avg = average(input);
fclose(input);
printf("The average of the numbers is %f.\n",avg);
return 0;
/* Data in data.txt
10 11 12 13 14 15. */
The average of the numbers is 12.5

5.4 RANDOM-ACCESS FILE


Individual records of a random-access file are normally fixed in length and may be
accessed directly (and thus quickly) without searching through other records.

This makes random-access files appropriate for :

● airline reservation systems


● banking systems
● point-of-sale systems
● other kinds of transaction-processing systems that require rapid access to
specific data.

Creating a Random-Access File


Functions fwrite and fread are capable of reading and writing arrays of data to and
from disk. The third argument of both fread and fwrite is the number of elements in
the array that should be read from or written to disk.

The following program open a random-access file, define a record format using a
struct, write data to the disk and close the file.

// Creating a random-access file sequentially


#include <stdio.h>
// clientData structure definition
struct clientData {
unsigned int acctNum; // account number
char lastName[ 15 ]; // account last name
char firstName[ 10 ]; // account first name
double balance; // account balance
}; // end structure clientData
int main( void ) {
unsigned int i; // counter used to count from 1-100

// create clientData with default information


struct clientData blankClient = { 0, "", "", 0.0 };
FILE *cfPtr; // credit.dat file pointer

// fopen opens the file; exits if file cannot be opened


if ( ( cfPtr = fopen( "credit.dat", "wb" ) ) == NULL ) {
puts( "File could not be opened." );
} // end if
else {

// output 100 blank records to file


for ( i = 1; i <= 100; ++i ) {
fwrite( &blankClient, sizeof( struct clientData ), 1, cfPtr );
} // end for
fclose ( cfPtr ); // fclose closes the file
} // end else
} // end main

Writing Data Randomly to a Random-Access File


The program writes data to the file "credit.dat". It uses the combination of fseek and
fwrite to store data at specific locations in the file.

Function fseek sets the file position pointer to a specific position in the file, then
fwrite writes the data.

// Writing data randomly to a random-access file


#include <stdio.h>
// clientData structure definition
struct clientData {
unsigned int acctNum; // account number
char lastName[ 15 ]; // account last name
char firstName[ 10 ]; // account first name
double balance; // account balance
}; // end structure clientData

int main( void ) {


FILE *cfPtr; // credit.dat file pointer

// create clientData with default information


struct clientData client = { 0, "", "", 0.0 };

// fopen opens the file; exits if file cannot be opened


if ( ( cfPtr = fopen( "credit.dat", "rb+" ) ) == NULL ) {
puts( "File could not be opened." );
} // end if
else {

// require user to specify account number


printf( "%s", "Enter account number"
" ( 1 to 100, 0 to end input )\n? " );
scanf( "%d", &client.acctNum );

// user enters information, which is copied into file


while ( client.acctNum != 0 ) {

// user enters last name, first name and balance


printf( "%s", "Enter lastname, firstname, balance\n? " );

// set record lastName, firstName and balance value


fscanf( stdin, "%14s%9s%lf", client.lastName,
client.firstName, &client.balance );
// seek position in file to user-specified record
fseek( cfPtr, ( client.acctNum - 1 ) *
sizeof( struct clientData ), SEEK_SET );

// write user-specified information in file


fwrite( &client, sizeof( struct clientData ), 1, cfPtr );

// enable user to input another account number


printf( "%s", "Enter account number\n? " );
scanf( "%d", &client.acctNum );
} // end while
fclose( cfPtr ); // fclose closes the file
} // end else
} // end main
Output:

Enter account number ( 1 to 100, 0 to end input ) ? 37


Enter lastname, firstname, balance ? Barker Doug 0.00
Enter account number ? 29
Enter lastname, firstname, balance ? Brown Nancy -24.54
Enter account number ? 96
Enter account number ?0
5.5 C GRAPHICS PROGRAMMING
This C Graphics tutorials is for those who want to learn fundamentals of Graphics
programming, without any prior knowledge of graphics. This tutorial contains many
fundamental graphics program like drawing of various geometrical shapes, use of
mathematical function in drawing
curves, colouring an object with different colours, patterns and simple animation
programs. This tutorial will provide you an overview of computer graphics and its
fundamentals.
Graphics programming in C using Turbo C provides a nostalgic journey for those who
started their programming journey in the DOS era. Turbo C was a popular integrated
development environment (IDE) that included a graphics library for simple graphics
programming. In this tutorial, we'll explore the basics of C graphics programming using
Turbo C, covering topics such as setting up the environment, drawing shapes, handling
input, and creating animations.
The first step in any graphics program is to initialize the graphics drivers on the
computer using initgraph method of graphics.h library.
void initgraph(int *graphicsDriver, int *graphicsMode, char *driverDirectoryPath);
It initializes the graphics system by loading the passed graphics driver then changing
the system into graphics mode. It also resets or initializes all graphics settings like color,
palette, current position etc, to their default values. Below is the description of input
parameters of initgraph function.
graphicsDriver : It is a pointer to an integer specifying the graphics driver to be used. It
tells the compiler that what graphics driver to use or to automatically detect the drive. In
all our programs we will use DETECT macro of graphics.h library that instruct
compiler for auto detection of graphics driver.
graphicsMode : It is a pointer to an integer that specifies the graphics mode to be used.
If *graphdriver is set to DETECT, then initgraph sets *graphmode to the highest
resolution available for the detected driver.
driverDirectoryPath : It specifies the directory path where graphics driver files (BGI
files) are located. If directory path is not provided, then it will search for driver files in
current working directory directory. In all our sample graphics programs, you have to
change path of BGI directory accordingly where you turbo C compiler is installed.
Colors in C Graphics Programming
There are 16 colors declared in C Graphics. We use colors to set the current drawing
color, change the color of background, change the color of text, to color a closed shape
etc. To specify a color, we can either use color constants like setcolor(RED), or their
corresponding integer codes like setcolor(4). Below is the color code in increasing
order.

COLOR INTEGER COLOR INTEGER


MACRO VALUE MACRO VALUE
BLACK 0 DARKGRAY 8
BLUE 1 LIGHTBLUE 9
GREEN 2 LIGHTGREEN 10
CYAN 3 LIGHTCYAN 11
RED 4 LIGHTRED 12
MAGENTA 5 LIGHTMAGENT 13
BROWN 6 A
YELLOW 14
LIGHTGRAY 7 WHITE 15
At the end of our graphics program, we have to unloads the graphics drivers and sets the
screen back to text mode by calling close graph function. Here is our first C Graphics
program to draw a straight line on screen.
/* C graphics program to draw a line */
#include<graphics.h>
#include<conio.h>
int main() {
int gd = DETECT, gm;
/* initialization of graphic mode */
initgraph(&gd, &gm, "C:\\TC\\BGI");
line(100,100,200, 200);
getch();
closegraph();
return 0;
}
In this program initgraph function auto detects an appropriate graphics driver and sets
graphics mode maximum possible screen resolution. Then line function draws a straight
line from coordinate (100, 100) to (200, 200). Then we added a call to getch function to
avoid instant termination of program as it waits for user to press any key. At last, we
unloads the graphics drivers and sets the screen back to text mode by calling closegraph
function.
Drawing Basic Shapes
Turbo C provides functions for drawing lines, circles, rectangles, and other shapes.
Here's an example:

#include <graphics.h>
#include <conio.h>
int main() {
int gd = DETECT, gm;
initgraph(&gd, &gm, "C:\\Turboc3\\BGI");
// Draw a line
line(100, 100, 200, 200);
// Draw a rectangle
rectangle(250, 150, 350, 250);
// Draw a circle
circle(500, 200, 50);
getch();
closegraph();
return 0;
}
In this example, we use the line, rectangle, and circle functions to draw basic shapes on
the graphics window.

You might also like