PPS - UNIT-III Notes
PPS - UNIT-III Notes
PREPROCESSORCOMMANDS:
A program which processes the source code before it passes through the compiler is known as
preprocessor
The commands of the preprocessor are known as preprocessor directives.
It begins with a # symbol.
They are never terminated with a semicolon.
1. FILEINCLUSION:
It is used to insert the contents of another file into the source code of the current file. There
are two slightly different ways to specify a file to be included: The name suggests you need to
include any file at the start of the program. The syntax of this directive is as follows:
Syntax:#include filename
The content that is included in the filename will be replaced at the point where the directive
iswritten.
By using the file inclusive directive, we can include the header files in the programs.
VignanInstituteofTechnology&Science
PPS (UNIT3)
Macros, function declarations, declaration of the external variables can all be combined in
the header
file instead of repeating them in each of the program.
The command for file inclusion is # include. This command loads the specified file into
theprogram.
Syntax: #include<filename.h>
#include"filename.h"
▪ Ifthefilenamegiveninangular brackets“<>”
thenthefilewillbesearchedonly(inthesystemdirectories)specified
listofdirectionsonly.
▪ Ifthefilenameisgivenindoublequotes“”,thenthefilewillbesearchedinthecurr entdirect
ory and also in the specified list of directories as mentioned in the include
searchpaththatmighthavebeensetup.
▪ Include search path is nothing but a list of directories that would be searched for
thefilebeingincluded.
EXAMPLE:#include<stdio.h>#include“prime.c”
/*PROGRAMTOILLUSTRATEABOUTMACROS-FILEINCLUSION*/
#include"stdio.h"
voidmain()
{
printf("\nObservethepreprocessorcommandsinthecode");getch();
}
O/P:Observethepreprocessorcommandsinthecode
2. MACRODEFINITION
A macro is a fragment of code which has been given a name. Whenever the name is used, it
is replaced by the contents of the macro.
There are two kinds of macros.
1. Object-like macros
2. function-like macros
1. Object-like macros:
• it is a simple identifier which will be replaced by a code fragment.
• It is called object-like because it looks like a data object in code that uses it.
• They are most commonly used to give symbolic names to numeric constants.
• To define object-like macros we can use #define directive.
Its Syntax: #define identifier value
Where #define - is apreprocessor directive used for text substitution.
identifier - is an identifier used in program which will be replaced by value.(In general the
identifiers are represented in captital letters in order to differentiate them from variable)
value -It is the value to be substituted for identifier.
•
When the preprocessor encounters this directive, it replaces any occurrence of
identifier in the rest of the code by replacement.
• This replacement can be an expression, a statement, a block or simply anything.
/*PROGRAMTOILLUSTRATEABOUTMACROS-MACRODEFINITION*/
#include<stdio.h>
#include"conio.h"
VignanInstituteofTechnology&Science
PPS (UNIT3)
#definetop10
voidmain()
{
inti=1;
for(;i<=top;i++)
printf(“\t%d”,i);
getch();
}
O/P:1 2 3 4 5 6 7 8 9 10
EX:
/*PROGRAMTOILLUSTRATEABOUTMACROS-MACRODEFINITION*/
#include<stdio.h>#inc
lude"conio.h"#define
p1 3.142voidmain()
{
floatr=1,area;a
rea=p1*r*r;
printf(“\n\tarea=%f”,area);
}
O/P:area=3.142000
float r = 3.5, x;
x = AREA (r);
printf ("\n Area of circle = %f", x);
}
• ___TIME___ defines the current time using a character literal in “HH:MM: SS” format.
Access specifier to print this is %s
• ___STDC___ specifies as 1 when the compiler complies with the ANSI standard. Access
specifier to print this is %d
• ___TIMESTAMP___ specifies the timestamp “DDD MM YYYY Date HH:MM: SS”. It is used to
define the date and time of the latest modification of the present source file. Access
specifier to print this is %s
• ___LINE___ consists of a present line number with a decimal constant. Access specifier to
print this is %d
• ___FILE___ includes the current filename using a string literal. Access specifier to print
this is %s
• ___DATE___ shows the present date with a character literal in the “MMM DD YYYY”
format.Access specifier to print this is %s
#include <stdio.h>
#include <stdlib.h>
int main()
{
printf("NULL : %d\n", NULL );
printf("EXIT_SUCCESS : %d\n", EXIT_SUCCESS );
printf("EXIT_FAILURE : %d\n", EXIT_FAILURE );
printf("RAND_MAX : %d\n", RAND_MAX );
printf("File Name : %s\n", FILE );
printf("DATE : %s\n", DATE );
printf("Line : %d\n", LINE );
return 0;
}
Output
NULL : 0
EXIT_SUCCESS : 0
EXIT_FAILURE : 1
RAND_MAX : 32767
File Name : BuiltinMacro.c
DATE : Aug 16 2017
Line : 12
floatr1=6,r2=2.5,a;clr
scr();a=AREA(r1);
printf("Area=%f",a);a=AREA(r2
);
printf("\nArea=%f",a);getch();
}
O/P:
Area=113.040001
Area=19.625
1. CONDITIONALCOMPILATION:
Ifwewant,wecanhavethecompilerskip
overpartofasourcecodebyinsertingpreprocessingcommands #ifdefand#endif.
Syntax: #ifdefidentifier
stt-1;
#else
stt-2;
#endif
EX: voidmain()
{
#ifdefINTEL
Codesuitableforintelpc#else
codesuitableformotorolapc#endif
Nextcodecommandtobothcomputers.
}
Uses of Conditional:
• use different code depending on the machine, operating system
• compile the same source file in two different programs
• to exclude certain code from the program but to keep it as a reference for future purposes
How to use conditional?
To use conditional, #ifdef, #if, #defined, #else and #elif directives are used.
#ifdef Directive
#ifdef MACRO
// conditional codes
#endif
Here, the conditional codes are included in the program only if MACRO is defined.
#if, #elif and #else Directive
#if expression
// conditional codes
#endif
Here, expression is an expression of integer type (can be integers, characters, arithmetic
expression, macros, and so on).
The conditional codes are included in the program only if the expression is evaluated to a non-
zero value.
VignanInstituteofTechnology&Science
The optional #else directive can be used with #if directive.
#if expression
conditional codes if expression is non-zero
#else
conditional if expression is 0
#endif
You can also add nested conditional to your #if...#else using #elif
#if expression
// conditional codes if expression is non-zero
#elif expression1
// conditional codes if expression is non-zero
#elif expression2
// conditional codes if expression is non-zero
#else
// conditional if all expressions are 0
#endif
#defined
The special operator #defined is used to test whether a certain macro is defined or not. It's
often used with #if directive.
VignanInstituteofTechnology&Science
PROGRAMTOILLUSTRATEABOUTMACROS:CONDITIONALCOMPILATION
#defineE=
voidmain()
{
int
a,b;#ifde
fE
a E10;
b E20;
#else
a=30;
b=40;
#endif
printf("\na=%d,b=%d",a,b);
}
OUTPUT:a=10,b=20
(Observebywritinganyother alphabetorexpressioninsteadEinthefunctionmain(
),youwillgettheoutputas30and40).
Example 1:
#include<stdio.h>
# define rectanglearea(a,b) (a*b)
# define upper 2
int main()
{
int a,b,area;
#ifdef upper
printf("enter a & b value");
scanf("%d%d",&a,&b);
area=rectanglearea(a,b);
printf("area of rectangle is %d",area);
#endif
Printf(“\n end of the program”):
return 0;
}
Output:
enter a & b value
57
area of rectangle is 35
end of the program
Example 2:
#include<stdio.h>
# define rectanglearea(a,b) (a*b)
# define upper 2
int main()
{
int a,b,area;
#ifdef u
printf("enter a & b value");
VignanInstituteofTechnology&Science
scanf("%d%d",&a,&b);
area=rectanglearea(a,b);
printf("area of rectangle is
%d",area);
#endif
Printf(“\n end of the program”):
return 0;
}
Output:
end of the program
Example:
int main()
{
#ifndef PI
#error "Include PI”
#endif
return 0;
VignanInstituteofTechnology&Science
}
Output
compiler error --> Error directive : Include PI
#line
It tells the compiler that next line of source code is at the line number which has been
specified by constant in #line directive
Syntax:
#line <line number> [File Name]
Where File Name is optional
Example:
int main()
{
#line 700
printf(Line Number %d”, LINE );
printf(Line Number %d”, LINE );
printf(Line Number %d”, LINE );
return 0;
}
Output
700
701
702
FILE
A file is anexternal collection of related data that a computer treats as a single unit.
• Computers store files to secondary storage so that the contents of files remain intact
when a computer turns off.
• When a computer reads a file, it copies the file from the storage device to memory; when it
writes to a file, it transfers data from memory to the storage device.
Let us look at a few reasons why file handling makes programming easier for all:
Reusability: File handling allows us to preserve the information/data generated after we run the
program.
• Saves Time: Some programs might require a large amount of input from their users. In
such cases, file handling allows you to easily access a part of a code using individual
commands.
• Commendable storage capacity: When storing data in files, you can leave behind the worry
of storing all the info in bulk in any program.
VignanInstituteofTechnology&Science
• Portability: The contents available in any file can be transferred to another one without any
data loss in the computer system. This saves a lot of effort and minimises the risk of
flawed coding.
VignanInstituteofTechnology&Science
Types of Files
When dealing with files, there are two types of files you should know about:
1. Text files
2. Binary files
When referring to file handling, we refer to files in the form of data files. Now, these data files are
available in 2 distinct forms in the C language, namely:
• Text Files
• Binary Files
Text Files
❖ The text files are the most basic/simplest types of files that a user can create in a C
program.
❖ We create the text files using an extension .txt with the help of a simple text editor.
❖ In general, we can use notepads for the creation of .txt files.
❖ These files store info internally in ASCII character format, but when we open these files,
the content/text opens in a human-readable form.
❖ Text files are, thus, very easy to access as well as use.
❖ But there’s one major disadvantage; it lacks security. Since a .txt file can be accessed
easily, information isn’t very secure in it. Added to this, text files consume a very large
space in storage.
To solve these problems, we have a different type of file in C programs, known as binary files.
Binary Files
VignanInstituteofTechnology&Science
❖ The binary files store info and data in the binary format of 0’s and 1’s (the binary number
system).
❖ Thus, the files occupy comparatively lesser space in the storage.
❖ In simpler words, the binary files store data and info the same way a computer holds the
info in its memory.
❖ Thus, it can be accessed very easily as compared to a text file.
❖ The binary files are created with the extension .bin in a program, and it overcomes the
drawback of the text files in a program since humans can’t read it; only machines can.
❖ Thus, the information becomes much more secure. Thus, binary files are safest in terms of
storing data files in a C program.
1. Create a stream
2. Open a file
3. Process a File
4. Close the file
1. Create a stream:
❖ we create a stream by declaring a file pointer of type FILE structure.
❖ ForExample: FILE* fp; here fp is a pointer to stream(stream pointer) which holds
the starting addressof stream.
2. Open a file:
❖ Once we create a file pointer we can open a file using the standard openfunction.
When the file is opened both file and stream are linked to each other.
❖ The file openfunction returns the address of file type, which is stored in stream
pointer variable fp.
Syntax: int FILE *fopen(const char *filename, const char *mode);
3. Processing a File(Read or write data):
❖ After creating the stream name we can use the stream pointer to useany stream
function (read or write) data using its corresponding stream.
❖ If a program reads datafrom a file then the stream used is Input Text Stream.
❖ If a program stores data to a file then thestream used is Output Text Stream.
❖ We can read the data till we reach the end of the file (EOF).
4. Close the file:
❖ once the file processing is completed we can close the file using closefunction.
❖ Closing breaks the link between the stream name and the file name.
❖ After closing the filethe contents on the stream are destroyed automatically since
stream is created on buffer (temporarymemory), which is also called as flushing
VignanInstituteofTechnology&Science
STANDARDI/OFUNCTIONS:
1. Fileopen/closefunctions
2. Characterinput/outputfunctions
3. Formattedinput/outputfunctions
4. Lineinput /outputfunctions
5. Blockinput/outputfunctions
6. Filepositioninginput/outputfunctions
7. Systemfileoperationsinput/outputfunctions
8. Filestatusoperationsinput/outputfunctions
Opening a File:
❖ Before any I/O (short of input/output) can be performed on a file you must open the file
first. fopen() function is used to open a file.
Syntax: FILE *fopen(const char *filename, const char *mode);
❖ filename: string containing the name of the file.
❖ mode: It specifies what you want to do with the file i.e read, write, append.
❖ On Success fopen() function returns a pointer to the structure of type FILE.
❖ FILE structure is defined in stdio.h and contains information about the file like name, size,
buffer size, current position, end of file etc.
❖ On error fopen() function returns NULL.
The possible value of modes are:
Opening Modes of C in Standard I/O of a Program
Mode Meaning of Mode When the file doesn’t exist
r Open a file for reading the content. In case the file doesn’t exist in the location,
then fopen() will return NULL.
rb Open a file for reading the content in In case the file doesn’t exist in the location,
binary mode. then fopen() will return NULL.
w Open a file for writing the content. In case the file exists, its contents are
overwritten.
In case the file doesn’t exist in the location,
then it will create a new file.
wb Open a file for writing the content in In case the file exists, then its contents will get
binary mode. overwritten.
In case the file doesn’t exist in the location,
then it will create a new file.
VignanInstituteofTechnology&Science
a Open a file for appending the content. In case the file doesn’t exist in the location,
Meaning, the data of the program is then it will create a new file.
added to the file’s end in a program.
ab Open a file for appending the content in In case the file doesn’t exist in the location,
binary mode. then it will create a new file.
Meaning, the data of the program is
added to the file’s end in a program in a
binary mode.
r+ Open a file for both writing and reading In case the file doesn’t exist in the location,
the content. then fopen() will return NULL.
rb+ Open a file for both writing and reading In case the file doesn’t exist in the location,
the content in binary mode. then fopen() will return NULL.
w+ Open a file for both writing and reading. In case the file exists, its contents are
overwritten.
In case the file doesn’t exist in the location,
then it will create a new file.
wb+ Open a file for both writing and reading In case the file exists, its contents are
the content in binary mode. overwritten.
In case the file doesn’t exist in the location,
then it will create a new file.
a+ Open a file for both appending and In case the file doesn’t exist in the location,
reading the content. then it will create a new file.
ab+ Open a file for both appending and In case the file doesn’t exist in the location,
reading the content in binary mode. then it will create a new file.
Note: mode is a string so you must always use double quotes around it.
Example: fopen("somefile.txt",'r');// Error
fopen("somefile.txt","r");// Ok
If you want to open several files at once, then they must have their own file pointer variable create
d using a separate call to fopen() function.
✓ File fp1 = fopen("readme1.txt", "r");
✓ File fp2 = fopen("readme2.txt", "r");
✓ File fp3 = fopen("readme3.txt", "r");
Here we are creating 3 file pointers for the purpose of reading three files.
fp=fopen("/home/downloads/list.txt","r");
It is important to note that Windows uses backslash character ('\') as a directory separator but
since C treats backslash as the beginning of escape sequence we can't directly use '\' character
inside the string. To solve this problem use two '\' in place of one '\' .
fp=fopen("C:\home\downloads\list.txt","r");// Error
fp=fopen("C:\\home\\downloads\\list.txt","r");// ok
Closing A File:
✓ When you are done working with a file you should close it immediately using the fclose()
function.
fgetc:
✓ Itisusedtoreadacharacterfromanydeviceincludingfile.(Ingeneralweuseforfiles).
✓ fgetc() is used to obtain input from a file single character at a time.
✓ This function returns the ASCII code of the character read by the function.
✓ It returns the character present at position indicated by file pointer.
✓ After reading the character, the file pointer is advanced to next character.
✓ If pointer is at end of file or if an error occurs EOF file is returned by this function.
✓ fgetc(), getc() and getchar() return the character read as an unsigned char cast to an intor
EOF on end of file or error.
SYNTAX:int fgetc(FILE *pointer)
pointer: pointer to a FILE object that identifiesthe stream on which the operation is to be
performed.
getc() is equivalent to fgetc() except that it may be implemented as a macro which
VignanInstituteofTechnology&Science
evaluates stream more than once.
SYNTAX:int fgetc(FILE *pointer)
✓ fgets() returns s on success, and NULL on error or when end of file occurs while
nocharacters have been read.
// C program to illustrate fgetc() function
#include <stdio.h>
int main ()
{
// open the file
FILE *fp = fopen("test.txt","r");
// Return if could not open file
if (fp == NULL)
return 0;
do
{
// Taking input single character at a time
char c = fgetc(fp);
// Checking for end of file
if (feof(fp))
break ;
printf("%c", c);
} while(1);
fclose(fp);
return(0);
}
Output:The entire content of file is printed character bycharacter till end of file. It reads newline
characteras well.
fputc()
✓ fputc() is used to write a single character at a time to a given file.
✓ It writes the given character at the position denoted by the file pointer and then advances
the file pointer.
✓ This function returns the character that is written in case of successful write operation
else in case of error EOF is returned.
Syntax: int fputc(int char, FILE *pointer)
char: character to be written. This is passed as its int promotion.
pointer: pointer to a FILE object that identifies the stream where the character is to be
written.
// C program to illustrate fputc() function
#include<stdio.h>
int main()
{
int i = 0;
FILE *fp = fopen("output.txt","w");
// Return if could not open file
if (fp == NULL)
return 0;
char string[] = "good bye", received_string[20];
for (i = 0; string[i]!='\0'; i++)
// Input string into the file
VignanInstituteofTechnology&Science
// single character at a time
fputc(string[i], fp);
fclose(fp);
fp = fopen("output.txt","r");
// Reading the string from file
fgets(received_string,20,fp);
printf("%s", received_string);
fclose(fp);
return 0;
}
Output: good bye
✓ When fputc() is executed characters of string variable are written into the file one by one.
✓ When we read the line from the file we get the same string that we entered.
putc/fputc:
fputc() writes the character c, cast to an unsigned char, to stream.
putc() is equivalent to fputc() except that it may be implemented as a macro which
fputc(), putc() and putchar() return the character written as an unsigned char cast to an
int or EOF on error.
✓ fputc function writes single character at a time to a given file.
✓ putc function writes a character to the specified stream.
✓ fputc function returns the characters written in a file or EOF on error.
✓ putc returns the character written as an unsigned char cast to an int or error.
✓ fputc works slower than putc.
✓ putc () takes a character argument, and outputs it to the specified FILE. fputc () does
exactly the same thing, and differs from putc () in implementation only.
/*P1PROGRAMTOWRITEANDREADTHEDATAINTOAFILE*/
#include<stdio.h>voidmain()
{
}
O/P:
EnterdatatoinsertintoaFile:
ThisistheContentofthefileABC.txt^Z (use ctrl+z to end the file)FileContents:
ThisistheContentof thefileABC.txt
/*PROGRAMTOREADANDPRINTCONTENTSOFAFILE */
#include<stdio.
h>voidmain()
{
charc,s[12]
;FILE
*fp;clrscr(
);RAVI:
VignanInstituteofTechnology&Science
printf("\nEnterFileNametoprint");s
canf("%s",s);
fp=fopen(s,"r
");if(fp!=NUL
L)
{
while((c=getc(fp))!=EOF)
{
putchar(c);
}
}
else
{
printf("\n File doesn't exist, Enter correct
name!");gotoRAVI;
}
fclose(f
p);getch
();
}
/*P3PROGRAMTOAPPENDANDREADTHEDATAINTOAFILE*/
#include<stdio.h
>voidmain()
{
char
c,s1[15];FILE
*fp;clrscr();
printf("\nEnteraFileNamewhichalreadyExist:");
gets(s1);fp=fopen(
s1,"a");
printf("\nEnter the data:
");while((c=getchar())!=EOF)
fputc(c,fp);fcl
ose(fp);fp=fopen(s1,"
r");
printf("\nThe whole data in the
File:\n",s1);while((c=fgetc(fp))!=EOF)
putchar(c);fc
lose(fp);getch();
}
O/P:
EnteraFileNamewhichalreadyExist:ABC.txt
Enter the data: The Data will be appended in the File using This
Program.^ZThewholedataintheFile:
ThisistheContentof thefileABC.txt
TheData willbeappended in theFileusingThisProgram.
VignanInstituteofTechnology&Science
VignanInstituteofTechnology&Science
/*P4 PROGRAM TO READ THE CONTENTS OF ONE FILE AND WRITE INTOANOTHERFILE*/
#include<stdio.h>voidmain()
{
charc;
FILE *fp1,*fp2;clrscr();
printf("\nEnter data in to file1: \n");
fp1=fopen("ABC.txt","w");
while((c=getchar())!=EOF)
fputc(c,fp1);fclose(fp1);
fp1=fopen("ABC.txt","r");
fp2=fopen("DEF.txt","w");
while((c=getc(fp1))!=EOF)
fputc(c,fp2);
fcloseall();
printf("\nYour data in another file2\n" );
fp2=fopen("DEF.txt","r");
while((c=getc(fp2))!=EOF)
putchar(c);
fclose(fp2);
}
Enterd 1:
ata Vignan Institute of Technology &Science^ZYourdatainanotherfile2
intofile VignanInstituteofTechnology&Science
• This program reads the whole content of the file, using this function by reading
characters one by one.
// C program to implement
// the above approach
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// Driver code
int main()
{
FILE* ptr;
char ch;
// Opening file in reading mode
ptr = fopen("test.txt", "r");
if (NULL == ptr) {
printf("file can't be opened \n");
}
printf("content of this file are \n");
// Printing what is written in file
// character by character using loop.
do {
ch = fgetc(ptr);
printf("%c", ch);
// Checking if character is not EOF.
// If it is EOF stop reading.
} while (ch != EOF);
VignanInstituteofTechnology&Science
// Closing the file
fclose(ptr);
return 0;
}
Input: Hai how are u
// C program to implement
// the above approach
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// Driver code
int main()
{
FILE* ptr;
char ch;
ptr = fopen("test.txt", "r");
if (NULL == ptr) {
printf("file can't be opened \n");
}
printf("content of this file are \n");
while (!feof(ptr)) {
ch = fgetc(ptr);
printf("%c", ch);
}
fclose(ptr);
return 0;
}
getw()andputw()functions:
Thegetw()andputw()areintegerorientedfunctions.
Theyaresimilartogetc,putcfunctions and areusedtoread and
writeintegers.Thesefunctionsareusefulwhenwedealwithonlyintegerstypeofd
ata.
Syntax: putw(integer variable, file
pointer);getw(fp);
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.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int num;
FILE *fptr;
// use appropriate location if you are using MacOS or Linux
fptr = fopen("C:\\program.txt","w");
if(fptr == NULL)
VignanInstituteofTechnology&Science
{
printf("Error!");
exit(1);
}
printf("Enter num: ");
scanf("%d",&num);
fprintf(fptr,"%d",num);
fclose(fptr);
return 0;
}
This program takes a number from the user and stores in the file program.txt.
After you compile and run this program, you can see a text file program.txt created in C drive of
your computer. When you open the file, you can see the integer you entered.
Example 2: Read from a text file:
#include <stdio.h>
#include <stdlib.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;
}
❖ This program reads the integer present in the program.txt file and prints it onto the screen.
❖ If you successfully created the file from Example 1, running this program will get you the
integer you entered.
❖ Other functions like fgetchar(), fputc() etc. can be used in a similar way.
C languagesuse the block inputand output functions to readand write data tobinary files.
When we read the binary files, the data will be transferred just as they
arefoundinmemory.Therearenoformatconversions.Thismeansthat,withtheexceptionofc
haracter data,wecan’t“see” thedatainbinaryfile; it lookslikehieroglyphics.
struct threeNum
{
int n1, n2, n3;
};
int main()
{
int n;
struct threeNum num;
FILE *fptr;
return 0;
}
In this program, we create a new file program.bin in the C drive.
We declare a structure threeNum with three numbers - n1, n2 and n3, and define it in the main
function as num.
Now, inside the for loop, we store the value into the file using fwrite().
The first parameter takes the address of num and the second parameter takes the size of the
structure threeNum.
Since we're only inserting one instance of num, the third parameter is 1. And, the last parameter
*fptr points to the file we're storing the data.
struct threeNum
{
int n1, n2, n3;
};
int main()
{
int n;
struct threeNum num;
FILE *fptr;
return 0;
}
In this program, you read the same file program.bin and loop through the records one by
one.
In simple terms, you read one threeNum record of threeNum size from the file pointed by
*fptr into the structure num.
FILEPOSITIONINGFUNCTIONS/RANDOMACCESSTOFILES:
Sofarwehavediscussedthefilefunctionsthatareusefulforthereadingandwritingthedata
sequentially. There are occasions, however, when we are interested in
accessingonlyaparticularpartofafileandnotinreadingtheotherparts.This
canbeachievedwiththehelpofthefunctionsfseek,ftellandrewind whichareavailableinthe
I/Olibrary.
ftell():
• Takesthefilepointerandreturnsanumberoftype“ long ”,thatcorrespondstothecurrent
position.Thisfunctionisusefulinsavingthecurrent positionofafile.
Ittakesthefollowingform
n=ftell(fp);
VignanInstituteofTechnology&Science
• n
wouldgivetherelativeoffset(inbytes)ofthecurrentposition.Thismeansthatnbytes
havealready beenread(orwritten).
rewind( ):
Ittakesafilepointerandresetsthepositiontothestartofthefile.Ittakesthefollowingform rewind(f
p);
ex: rewind(fp);n=ftell(fp);
Thisstatementwouldassign0tonbecausethefilepositionhasbeensettothestartofthefil
ebyrewind .
Rememberthatthefirstbyteinthefileisnumberedas0,secondas1,andsoon.
fseek():
fseek isafunctionusedtomovethefilepointer(position)todesiredlocationwithinfile.
Ittakes thefollowingform.
fseek(fp,offset,position);
✓ fpisthefilepointerconcerned.
✓ offsetisthenumberorvariableoftypelong.
✓ positionisanintegernumber.
Theoffsetspecifiesthenumberof
positions(bytes)tobemovedfromthelocationspecifiedbytheposition.
Thepositioncantakeoneofthefollowingthreevalues:
Value Meaning
0 Beginningofthefile
1 Currentposition
2 Endofthefile
ThethreevaluesaredefinedusingsomeconstantnamesintheheaderfileDifferentposition
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.
SEEK_CUR Starts the offset from the current location of the cursor in the file.
Statement Meaning
fseek(fp,0L,0) ---------- GototheBeginningofthefile(similartorewind()).
fseek(fp,2L,1) ----------- Movesthefilepointer 2bytesintheforwarddirectionfromthe
currentpositionofthefile.
fseek(fp,-2L,2) --------- Movesafilepointer2bytesinbackwarddirectionfromtheend
ofthefile.
fseek(fp,0L,1) ----------- Stayatthecurrentposition.(Rarelyused).
fseek(fp,m,0) ----------- Moveto(m+1)thbyteinthefile.
fseek(fp,m,1) ----------- Goforwardbymbytes.
fseek(fp,-m,2) ---------- Gobackwardbymbytesfromtheend.(Positionsthefiletothe
mthcharacterfromtheend.
• Whenoperationissuccessful,fseekreturnsaZero.Ifweattempttomovethefilepointerbeyo
ndthefile boundaries,anerroroccursan fseekreturns -1.
include <stdio.h>
#include <stdlib.h>
struct threeNum
{
VignanInstituteofTechnology&Science
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");
This program will start reading the records from the file program.bin in the reverse order
(last to first) and prints it.
FILESTATUSOPERATIONSINPUT/OUTPUTFUNCTIONSERRORHANDLINGDURINGI/OOPEPR
ATIONS:
• Itispossiblethatan errormayoccurduringtheI/Ooperationsonafile.Typicalerrorsituations
include:
• Tryingtoreadbeyondtheend-of-filemark.
• Deviceoverflow.
• Tryingtouseafilethathasnotbeenopened.
• Tryingtoperformanoperationonafile,whenthefileisopenedforanothertypeofoperation
• Openingafilewithaninvalidfilename.
• Attemptingtowritetoawrite-protectedfile.
If we fail to check such reead and write errors, a program may behave
abnormallywhenanerroroccurs.Anuncheckederrormayresultinaprematureterminationoftheprogram
orincorrectoutput.
WehavethreestatusenquirylibraryfunctionsinC,
Totestendof file : feof(fp)
Totesterror : ferror(fp)
Toclearerror : clearerr(fp)
feof(fp):
• The end of file error feof(fp) function is used to check if the end of file has beenreached.
o Ifthefilepointerisattheend–i.e.,ifallthedatahavebeenread–
thefunctionreturnsnonzero(true).
• Iftheendofthefilehas notbeenreached,zero(false)isreturned.
• Thefunctiondeclarationcanbeif(feof(fp))
printf(“Endoffile”);
VignanInstituteofTechnology&Science
ferror(fp):
• TheTesterrorferror(fp)functionisusedtochecktheerrorstatusofthefile.
• Errorscanbecreatedformanyreasons,rangingrombadphysicalmedia(diskortape)to
illogicaloperations,suchastryingtoreadafileinwritestate.
• Theferrorfunctionreturnstrue(nonzero)ifanerrorhasoccurred.
• Itreturnsfalse(zero)ifnoerrorhasoccurred.
• Thefunctiondeclarationcanbewrittenasif(ferror(fp)!=0)
printf(“Anerrorhasbeenoccurred”);
We know that wheneer a file is opened using “fopen” function, a file pointer is returned.
Ithefilecannotbeopenedforsomereason,thenthefunctionreturnsaNULLpointer.Thisfacilitycanbeused
totestwhetherafilehasbeenopenedornot.
if(fp==NULL)
printf(“Filecan’tbeopened”);
clearer(fp):
When an error occurs, the subsequent calls to ferrorreturn nonzero, until the errorstatusof
thefileisreset. Thefunction clearer()isused forthispurpose.
voidclearer(fp);
VignanInstituteofTechnology&Science
/*P17PROGRAMTOILLUSTRATEABOUTfeof()TOFINDTHEENDOFFILE*/
#include<stdio.h
>voidmain()
{
FILE
*fp;inti,n;
fp=fopen("ABCD.txt","w+");
clrscr();for(i=0;i<100;i+=10)
{
putw(i,fp);
}
rewind(fp);
printf("\nContent of the
file");for(i=0;i<20;i++)
{
n=getw(fp);
if(feof(fp))
{
else
printf("%d",n);
}}
SYSTEMFILEOPERATIONFUNCTIONS:
remove,rename,tempfile;
i)remove():
Itisusedtodeleteafilepermanentlyfromthedisc.
Syntax:remove(“filename”);i
i)rename():
It is used to change the name of an existing
file.Syntax:rename(“existing
filename”,”newfilename”);Ex:
rename(“prime.c”,”primenum.c”);
tempfile():
Itcreatesatemporaryfilewhichcanbeusedtostoresomedatatemporarilyduringthe
executionoftheprogram.
VignanInstituteofTechnology&Science
Additions
PROGRAMTOWERSOFHONAI
#include"stdio.h"
voidtowers(int,char,char,char);
voidtowers(intn,charfrompeg,chartopeg,charauxpeg)
{/*Ifonly1disk,makethemoveandreturn*/if(n==1)
{ printf("\nMove disk 1 from peg %c to peg
%c",frompeg,topeg);return;
}
/*Movetopn-1disksfromAtoB,usingCasauxiliary*/towers(n-
1,frompeg,auxpeg,topeg);
/* Moveremainingdisksfrom AtoC*/
printf("\nMovedisk%dfrompeg%ctopeg%c",n,frompeg,topeg);
/* Moven-
1disksfromBtoCusingAasauxiliary*/towers(n-
1,auxpeg,topeg,frompeg);
}
main()
{intn;
printf("Enterthenumberofdisks:");scanf(
"%d",&n);
printf("The Tower of Hanoi involves the moves
:\n\n");towers(n,'A','C','B');
return0;
}
O/P:
Enterthenumberofdisks:4
TheTower of Hanoiinvolvesthe moves:
VignanInstituteofTechnology&Science
PROGRAMTOCONVERTTHENUMBERINWORDS(VERSION1)
/*numwords.c-Convertsnumbersintowords*/
#include
<stdio.h>#include<s
tdlib.h>char
line[80];
/*thelinebuffer. Stores thenumbers as
chars*/inti;/*justaforloopcounter*/
intmain(void)
{
printf("\n\nnumwords\nConverts numbers into
words\n");while(1){
printf("Pleasewriteanumber(oranythingelsetoquit):");fgets(line
,sizeof(line),stdin);
line[strlen(line)-1]='\0';
for(i=0;i<strlen(line);++i){/*thisfortraversesthroughthecharacterarraythatstoredt
henumber*/
switch(line[i])
{/*...Andthisswitchcomesupwitheachdigitasword.*/case'0':{
printf("zero
");break;
}
case'1':{
printf("one
");break;
}
case'2':{
printf("two
");break;
}
case'3':{
printf("three");br
eak;
}
case'4':{
printf("four
");break;
}
case'5':{
printf("five
");break;
}
case'6':{
printf("six
VignanInstituteofTechnology&Science
");break;
}
case'7':{
printf("seven");br
eak;
}
case'8':{
printf("eight");break;
}
case'9':{
printf("nine
");break;
}
default:{
printf("That's not a valid
number\n");return(0);
}
}
}
printf("\n");/*wewantacarriagereturnafterthenumbercompletes.*/
/* system("PAUSE"); //this stt is for my reference Good in Windows / Dev-cpp
tokeeptheconsolewindowfromclosingautomatically.DeleteitinLinux.*/
}
return0;
}
Output:
numwords Convertsnumbersintowords
Pleasewriteanumber(oranythingelsetoquit):12345onetw
othreefourfive
Pleasewriteanumber(oranythingelsetoquit):0890zeroei
ghtninezero
Pleasewriteanumber(oranythingelsetoquit):AThat'sn
otavalidnumber.
PROGRAMTOCONVERTTHENUMBERINWORDS(VERSION2)
/*ProgramtoConvertNumbersintoWords*/
#include<stdio.h>
voidpw(long,char[]);
char *one[]={"","one","two","three","four","five","six","seven","eight","
Nine","ten","eleven","twelve","thirteen","fourteen","fifteen","sixteen","seventeen",
VignanInstituteofTechnology&Science
"eighteen","nineteen"};
char*ten[]={"","","twenty","thirty","forty","fifty","sixty","seventy","eighty","ninety"};
voidmain()
{
long
n;clrscr()
;
printf("Enter any number(max 9 digits):
");scanf("%9ld",&n);
if(n<=0)
printf("Enternumbersgreaterthan0");els
e
{
pw((n/10000000),"crore");
pw(((n/100000)%100),"lakh");
pw(((n/1000)%100),"thousand");
pw(((n/100)%10),"hundred");
pw((n%100),"");
}
getch();
}
voidpw(longn,charch[])
{
(n>19)?printf("%s%s",ten[n/10],one[n%10] :printf("%s",one[n]);
if(n)
printf("%s",ch);
}
Output:
Enteranynumber(max9digits):987654321
ninetyeightcroreseventysixlakhfiftyfourthousandthreehundredtwentyone
PROGRAMTOCONVERTINTEGERTOBINARY:/*PROGRAMTONUMBERTOBINARY*/
#include<stdio.h>
#include<conio.h
>intmain()
{
int
temp,binary[10],count=0,number,index=0;pri
ntf("Enter a (DECIMAL) number:
");scanf("%d",&number);
VignanInstituteofTechnology&Science
printf("\nValue %d in binary
",number);while(number>0)
{
count++;temp=numbe
r;number=number/2;
binary[index]=temp%
2;index++;
}
for(index=count-1;index>=0;index--)
{
printf(" %d",binary[index]);
}
getch();r
eturn0;
}
OUTPUT:
Entera(DECIMAL)number:567
Value567inbinary:1000110111
VignanInstituteofTechnology&Science
PROGRAMTOCONVERTINTEGERTOROMANNUMBER:
#include<stdio.h>
#include<conio.h
>
intConvertToRomanNo(intnumber,intno,charch);i
ntmain()
{
intnumber;
printf("Enter a DECIMAL Number to convert into ROMAN
Number::");scanf("%d",&number);
printf("Roman number of" " %d "
"is::",number);number=ConvertToRomanNo(num
ber,1000,'M');number=ConvertToRomanNo(numb
er,500,'D');number=ConvertToRomanNo(number,
100,'C');number=ConvertToRomanNo(number,50,'
L');number=ConvertToRomanNo(number,10,'X');n
umber=ConvertToRomanNo(number,5,'V');numb
er=ConvertToRomanNo(number,1,'I');
getch();r
eturn0;
}
intConvertToRomanNo(intnumber,intno,charch)
{
int
i,j;if(number=
=9)
{
printf("IX");return(
number%9);
}
if(number==4)
{
printf("IV");return(
number%4);
}
j=number/no;for(i
=1;i<=j;i++)
{
printf("%c",ch);
VignanInstituteofTechnology&Science
}
return(number%no);
}
Output:
EnteraDECIMALNumbertoconvertintoROMANNumber::1234
Romannumberof1234is::MCCXXXIV
PROGRAMTOCONVERTROMANNUMERALTOINTEGER:
/*CodeToConvertRomanNumeralToInteger*/
#include<stdio.h>
#include<conio.h
>main()
{
int n=0,i=0,x=0,ax=0,bx=0,cx=0,dx=0,ex=0,fx=0,gx=0,g[10],a[10],b[10],c[10],d[10],e[10],f[10];
charr[10];
printf("please enter the roman numeral
:");scanf("%s",&r);
for(;i<10;i++)
{
switch(r[i])
{
case'I':
a[ax]=i;++ax;break;case'V':
b[bx]=i;++bx;break;case'X':
c[cx]=i;++cx;break;case'L':
d[dx]=i;++dx;break;case'C':
e[ex]=i;++ex;break;case'D':
f[fx]=i;++fx;break;case'M':
g[gx]=i;++gx;break;default: ;
}
}
for(i=0;r[i]!=0;i++)
{x+
+;
}
n=
1000*(gx);for(i=0;i
<fx;i++)
{
if(gx==0)
n=500*fx;
else if(f[i]>g[gx-
1])n=n+500;
elsen=n
-500;
}
VignanInstituteofTechnology&Science
for(i=0;i<ex;i++)
VignanInstituteofTechnology&Science
{
if(gx==0&fx==0)
n=100*ex;
else if(fx==0&gx!=0&e[i]<g[gx-
1])n=n-100;
else if(fx==0&gx!=0&e[i]>g[gx-
1])n=n+100;
else if(fx=!0&gx==0&e[i]<f[fx-
1])n=n-100;
else if(fx=!0&gx==0&e[i]>f[fx-
1])n=n+100;
else if(fx=!0&gx!=0&e[i]>f[fx-1]&e[i]>g[gx-
1])n=n+100;
else if(fx=!0&gx!=0&e[i]>g[gx-1]&e[i]<f[fx-1])n=n-
100;
}
n=((50*dx)+n);
n=
((10*cx)+n);for(i=
0;i<cx;i++)
{
if(c[i]<e[ex-1]&c[i]<d[dx-
1])n=n-20;
}
n=((5*bx)+n);
n=
((1*ax)+n);for(i=0;i
<ax;i++)
{
if(a[i]<b[bx-1]&a[i]<c[cx-
1])n=n-2;
}
printf("value is %d
",n);getch();
return0;
}
/*SOMEERRORISTHEREINTHEPROG
*/OUTPUT:
pleaseentertheromannumeral:MCCXXXIV
valueis1236
(ITIS1234….NOT1236)
Lefttothe aspiranttoresolve it
VignanInstituteofTechnology&Science