COURSE TITLE: SOFTWARE DEVELOPMENT VI
COURSE CODE: VIT 351
TOPICS COVERED:
FILES
FILES I/O STREAM
TYPES OF FILES
DRAWBACKS OF TRADITIONAL METHOD OF DATA STORAGE
CONCEPT OF BUFFER
MODES OF FILE OPENING
END OF FILE
PROCESSORS DIRECTIVES
MACROS
TYPES OF MACROS
DIFFERENCE BETWEEN MACROS AND FUNCTIONS
QUIZ SET 5
1. D.E.I. TECHNICAL COLLEGE
COURSE TITLE: Software Development-VI
SLIDE-5
COURSE CODE: VIT351
CLASS: DIPLOMA IN INFORMATION TECHNOLOGY VOCATIONAL (1ST YEAR)
SESSION: 2019-20
2. TOPICS COVERED
FILES I/O STREAM
FILES IN C
CONCEPT OF BUFFER
MODES IN FILE
END OF FILE
PREPROCESSORS AND MACROS
DIFFERENCE BETWEEN MACROS AND FUNCTIONS
QUIZ SET 5
3. File I/O Streams in C Programming Language :
In C all input and output is done with streams
Stream is nothing but the sequence of bytes of data
A sequence of bytes flowing into program is called input stream
A sequence of bytes flowing out of the program is called output stream
Use of Stream make I/O machine independent.
Predefined Stream or predefined File Pointer:
stdin Standard Input
stdout Standard Output
stderr Standard Error
GO TO TOPICS
4. Drawbacks of Traditional I/O System
Until now we are using Console Oriented I/O functions.
“Console Application” means an application that has a text-based
interface. (black screen window))
Most applications require a large amount of data , if this data is entered
through console then it will be quite time consuming task
Main drawback of using Traditional I/O :- data is temporary (and will not be
available during re-execution )
5. Files in C
A file is a space in a memory where data is stored.
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 ready made
structure.
'C' programming provides various functions to deal with a file.
A mechanism of manipulating with the files is called as file management.
There are two kinds of files in a system. They are,
1. Text files (ASCII)
2. Binary files
Text files contain ASCII codes of digits, alphabetic and symbols.
Binary file contains collection of bytes (0’s and 1’s). Binary files are compiled version of
text files.
GO TO TOPICS
6. What are Text Files?
Binary Files Contain Information Coded Mostly in Binary Format.
Binary Files are difficult to read for human.
Binary Files can be processed by certain applications or processors.
Only Binary File Processors can understood Complex Formatting Information Stored in
Binary Format.
Humans can read binary files only after processing.
All Executable Files are Binary Files.
What are Binary Files ?
Text File is Also Called as “Flat File“.
Text File have .txt Extension.
Text File Format have Little contains very little formatting .
Text File Format is Basic File Format in C Programming.
Text File is simple Sequence of ASCII Characters.
Each Line is Characterized by EOL Character (End of Line).
7. File Handling in C
New way of dealing with data is file handling.
Data is stored onto the disk and can be retrieve whenever require.
Output of the program may be stored onto the disk
In C we have many functions that deals with file handling
A file is a collection of bytes stored on a secondary storage device (generally a disk)
Collection of byte may be interpreted as –
Single character
Single Word
Single Line
Complete Structure.
GO TO TOPICS
8. Why files are needed?
Reusability: It helps in preserving the data or information generated after
running the program.
Large storage capacity: Using files, you need not worry about the problem of
storing data in bulk.
Saves time: There are certain programs that require a lot of input from the user.
You can easily access any part of the code with the help of certain
commands.
Portability: You can easily transfer the contents of a file from one computer
system to another without having to worry about the loss of data.
9. Concept of Buffer
Buffer is an area in memory where the data is temporarily
stored before being written to the file. When we open a file, a
buffer is automatically associated with its file pointer.
A File can be used to store a large volume of persistent data.
Like many other languages 'C' provides following file
management functions,
1. Creation of a file
2. Opening a file
3. Reading a file
4. Writing to a file
5. Closing a file
GO TO TOPICS
10. File Input/Output in C
In C language, we use a structure pointer of file type to declare a file.
FILE *fp;
Function description
fopen() create a new file or open a existing file
fclose() closes a file
getc() reads a character from a file
putc() writes a character to a file
fscanf() reads a set of data from a file
fprintf() writes a set of data to a file
getw() reads a integer from a file
putw() writes a integer to a file
fseek() set the position to desire point
ftell() gives current position in the file
rewind() set the position to the beginning point
11. How to Create a File?
Whenever you want to work with a file, the first step is to create a file. A file is nothing
but space in a memory where data is stored.
To create a file in a 'C' program following syntax is used,
FILE *fp;
fp = fopen(const char *filename, const char *mode);
fp is a file pointer which points to the type file.
In the above syntax, the file is a data structure which is defined in the standard library.
fopen is a standard function which is used to open a file.
If the file is not present on the system, then it is created and then opened.
If a file is already present on the system, then it is directly opened using this function.
12. File opening mode description
r
Open a file for reading. If a file is in reading mode, then no data is deleted if a
file is already present on a system.
w
Open a file for writing. If a file is in writing mode, then a new file is created if a
file doesn't exist at all. If a file is already present on a system, then all the data
inside the file is truncated, and it is opened for writing purposes.
a
Open a file in append mode. If a file is in append mode, then the file is opened.
The content within the file doesn't change.
r+ open for reading and writing from beginning
w+ open for reading and writing, overwriting a file
a+ open for reading and writing, appending to file
GO TO TOPICS
13. Closing a file
One should always close a file whenever the operations on file are over. It means the
contents and links to the file are terminated. This prevents accidental damage to the
file.
'C' provides the fclose function to perform file closing operation. The syntax of fclose is
as follows,
fclose (file_pointer);
Example:
FILE *fp;
fp = fopen ("data.txt", "r");
fclose (fp);
It returns 0 if close was successful and EOF (end of file) if there is an error has occurred
while file closing.
14. End of File
The file reading functions need to know the end of file so that they can stop
reading.
When the end of file is reached, the operating system sends an end-of-file signal
to the program.
When the program receives this signal, the file reading functions return EOF,
which is a constant defined in the file stdio.h and its value is -1.
EOF is an integer value, so make sure that the return value of the function is
assigned to an integer variable.
Note that the value EOF is not present at the end of the file, it is returned by the
file reading functions when end of file is reached.
GO TO TOPICS
16. I/O operation on File using fscanf() & fprintf()
#include<stdio.h>
struct emp
{
char name[10];
int age;
};
int main()
{
struct emp e;
FILE *p,*q;
p = fopen("record.txt", "a");
q = fopen("record.txt", "r");
printf("Enter Name and Age:");
scanf("%s %d", e.name, &e.age);
fprintf(p,"%s %d", e.name, e.age);
fclose(p);
do
{
fscanf(q,"%s %d", e.name, e.age);
printf("%s %d", e.name, e.age);
}
while(!feof(q));
}
17. Example: C program to read name and marks of n number of students and store
them in a file.
#include <stdio.h>
#include <stdlib.h>
int main()
{
char name[50];
int marks, i, num;
printf("Enter number of students: ");
scanf("%d", &num);
FILE *fptr;
fptr = (fopen("stud1.txt", "w"));
if(fptr == NULL)
{
printf("Error!");
exit(1);
}
for(i = 0; i < num; ++i)
{
printf("For student%dnEnter name: ", i+1);
scanf("%s", name);
printf("Enter marks: ");
scanf("%d", &marks);
fprintf(fptr,"nName: %s nMarks=%d n", name,
marks);
}
fclose(fptr);
return 0;
}
18. Example: C program to write all the members of an array of structures to a file using
fwrite(). Read the array from the file and display on the screen.
#include <stdio.h>
struct student
{
char name[50];
int height;
};
int main(){
struct student s1[5], s2[5];
FILE *fptr;
int i;
fptr = fopen("record2.txt","wb");
for(i = 0; i < 5; ++i)
{
fflush(stdin);
printf("Enter name: ");
gets(s1[i].name);
printf("Enter height: ");
scanf("%d", &s1[i].height);
}
fwrite(s1, sizeof(s1), 1, fptr);
fclose(fptr);
fptr = fopen(“record2.txt", "rb");
fread(s2, sizeof(s2), 1, fptr);
for(i = 0; i < 5; ++i)
{
printf("Name: %snHeight: %d", s2[i].name, s2[i].height);
}
fclose(fptr);
}
20. Preprocessor
The program which
processes the source
code before it is
compiled in the
compiler.
Preprocessing
The process of
processing the code
by the preprocessor
Preprocessor
Directives
Commands used in
preprocessor
21. What is Preprocessor?
Preprocessor directive is a text substitution tool that instruct the compiler to pre-processor
our program before its actual compilation.
The C preprocessor is a macro preprocessor (allows you to define macros) that
transforms your program before it is compiled. These transformations can be the
inclusion of header file, macro expansions etc.
The word “pre” means “before” and the word “processor” refers to “making something”.
Command used in pre-processor are called pre-processor directives.
Macros are nothing but a piece of code based on the #define preprocessor.
All preprocessing directives begin with a # symbol.
For example,
#define PI 3.14
22. Advantages of Preprocessor
Programs easier to develop
Easier to read
Easier to modify
C code more transportable between different
machine architectures.
Types of Preprocessor Directives
The list of preprocessor directives are:
Macro
Header file inclusion
Conditional compilation
Other directives
23. Predefined Macros
There are a number of macros automatically pre-defined by the compiler, including the
following list.
Note that each one begins and ends with TWO underscore characters:
__LINE__ - The line number of the current file being compiled as a decimal constant.
__FILE__ - The name of the current file being compiled as a string literal.
__DATE__ - Used to represent the current date in “MM DD YYYY” format.
__TIME__ - The current time as a character literal in “HH:MM:SS” format.
__STDC__ – Used to indicate when the compiler compiles the code successfully by
returning the value 1.
25. 1 #define Substitutes a preprocessor macro
2 #include Inserts a particular header from another file.
3 #undef Undefines a preprocessor macro.
4 #ifdef Returns true if this macro is defined.
5 #ifndef Returns true if this macro is not defined.
6 #if Tests if a compile time condition is true.
7 #else The alternative for #if.
8 #elif #else and #if in one statement.
9 #endif Ends preprocessor conditional.
10 #error Prints error message on stderr
11 #pragma
Issues special commands to the compiler, using a standardized
method
26. #include
The #include preprocessor is used to include header files to C programs. For example,
#include <stdio.h>
You can also create your own header file containing function declaration and include it
in your program using this preprocessor directive.
#include "my_header.h"
Let's start with macro, as we discuss, a macro is a segment of code which is replaced by
the value of macro. Macro is defined by #define directive.
Syntax
#define token value
There are two types of macros:
1. Object-like Macros
2. Function-like Macros
#define
27. Example: A
#include<stdio.h>
#define MESSAGE “I am a student of Information Technology“
int main()
{
printf("n MESSAGE : %s ",MESSAGE);
return 0;
}
#include<stdio.h>
#define WRONG 0
#define RIGHT 1
int main()
{
printf("nWRONG IS : %f",WRONG);
printf("nRIGHT IS : %d",RIGHT);
return 0;
}
Example: B
1. Object-like Macros
The object-like macro is
an identifier that is
replaced by value. It is
widely used to represent
numeric constants.
For example:
28. Example: C
#include <stdio.h>
#define MIN(a,b) ((a)<(b)?(a):(b))
int main() {
printf("Minimum between 10 and 20 is: %dn", MIN(10,20));
return 0;
}
2. Function-like Macros
The function-like macro looks like function call. For example:
#define MIN(a,b) ((a)<(b)?(a):(b))
Here, MIN is the macro name.
29. Preprocessor Formatting
A preprocessing directive cannot be more than one line in normal circumstances. It
may be split cosmetically with Backslash-Newline.
Comments containing Newlines can also divide the directive into multiple lines.
for example, you can split a line cosmetically with Backslash-Newline anywhere:
/*
*/ # /*
*/ defi
ne FO
O 10
20
is equivalent into #define FOO 1020.
30. #undef
To undefine a macro means to cancel its definition. This is done with the #undef directive.
Undefines a symbol specified by <identifier> which was previously defined with a #define
directive.
• #undef Directive is used to undefine any Macro Symbol.
• #undef can undefine only “User Defined” Macro’s.
• #undef cannot undefine “Global Macro Identifiers“.
• #undef is used where we have to redefine any Macro Identifier.
Syntax:
#undef token
define and undefine example
Example:
#include <stdio.h>
#define PI 3.1415
#undef PI
main() {
printf("%f",PI);
}
31. Conditional Compilation
In C programming, you can instruct preprocessor whether to include a block of code or
not. To do so, conditional directives can be used.
It's similar to a if statement with one major difference.
The if statement is tested during the execution time to check whether a block of code
should be executed or not whereas, the conditionals are used to include (or skip) a block
of code in your program before execution.
Uses of Conditional
o use different code depending on the machine, operating system
o compile same source file in two different programs
o to exclude certain code from the program but to keep it as reference for future purpose
To use conditional, #ifdef, #if, #defined, #else and #elseif directives are used.
32. #ifdef
The #ifdef preprocessor directive checks if macro is defined by #define. If yes, it executes
the code.
Syntax:
#ifdef MACRO
//code
#endif
#ifndef
The #ifndef preprocessor directive checks if macro is not defined by #define. If yes, it
executes the code.
Syntax:
#ifndef MACRO
//code
#endif
33. #if
The #if preprocessor directive evaluates the expression or condition. If condition is true, it
executes the code.
Syntax:
#if expression
//code
#endif
#else
The #else preprocessor directive evaluates the expression or condition if condition of #if is
false. It can be used with #if, #elif, #ifdef and #ifndef directives.
Syntax:
#if expression
//if code
#else
//else code
#endif
34. #elif
Syntax with #elif
#if expression
//if code
#elif expression
//elif code
#else
//else code
#endif
#error
The #error preprocessor directive indicates error. The compiler
gives fatal error if #error directive is found and skips further
compilation process.
Syntax:
#error error_message
#pragma
It depends on the compiler as different OS and different
machines provide all types of operating system feature which
is used by the compiler to offer additional information to the
compiler.
Syntax:
#pragma token
35. This preprocessor directive is generally used in three ways which are
a. #pragma startup
b. #pragma exit
c. #pragma warn
#pragma startup:
This is used to call some function right from the start up (before executing main() function).
We can call any function by using this preprocessor directive.
Syntax: #pragma startup funcall
In the above code “funcall” function will be called from the start up of the program.
#pragma exit:
It is a counter part of start up. It is used to call some function when program ends.
Syntax: #pragma exit funcall
In the above code “funcall” function is called at the exit of the program.
#pragma warn:
This preprocessor directive is used very rarely. It is generally used to supress a specific
warning inside a program.
36. EXAMPLE PROGRAM FOR #IFDEF, #ELSE AND #ENDIF IN C:
#include <stdio.h>
#define VIT 100
int main()
{
#ifdef VIT
printf("VIT is defined. So, this line will be added in "
"this C filen");
#else
printf("VIT is not definedn");
#endif
return 0;
}
37. EXAMPLE PROGRAM FOR #IFNDEF AND #ENDIF IN C:
#include <stdio.h>
#define VIT 100
int main()
{
#ifndef TESSA
{
printf("TESSA is not defined. So, now we are going to "
"define heren");
#define TESSA 300
}
#else
printf("TESSA is already defined in the program”);
#endif
return 0;
}
38. EXAMPLE PROGRAM FOR #IF, #ELSE AND #ENDIF IN C:
#include <stdio.h>
#include <stdlib.h>
#define a 300
int main()
{
#if (a==300)
printf("This line will be added in this C file since "
"a = 300n");
#else
printf("This line will be added in this C file since "
"a is not equal to 300n");
#endif
return 0;
}
39. Example: #error
#include<stdio.h>
#ifndef __MATH_H
#error First include then compile
#else
void main(){
float a;
a=sqrt(7);
printf("%f",a);
}
#endif
Example: #pragma
#include<stdio.h>
#include<conio.h>
void func() ;
#pragma startup func
#pragma exit func
void main()
{
printf("nI am in main");
getch();
}
void func()
{
printf("nI am in func");
getch();
}
40. Difference between Macros and Function
S No Macro Function
1
Macro is Preprocessed Function is Compiled
2
No Type Checking Type Checking is Done
3 Code Length Increases Code Length remains Same
4 Use of macro can lead
to side effect
No side Effect
5 Speed of Execution is
Faster
Speed of Execution is Slower
6
Before Compilation macro name is replaced
by macro value
During function call , Transfer of Control takes
place
7
Useful where small code appears many time Useful where large code appears many time
8 Generally Macros do not extend beyond one
line
Function can be of any number of lines
9
Macro does not Check Compile Errors Function Checks Compile Errors
GO TO TOPICS
42. 1. Which header file is responsible for file handling features?
A. stdlib.h
B. stdio.h
C. stdfile.h
D. All three
2. What is the difference in printf() and fprintf() function?
A. printf() does not use a pointer to FILE object
B. printf() cannot be used for file output
C. fprintf() can be used only for file output
D. All above are true
GO TO TOPICS
43. 3. What is the difference between fputc() and fputs().
A. fputc() is for writing character and fputs() writes a string
B. They both work in similar way
C. fputs() is for character output and fputc() is for strings
D. fputs() is not a valid C function
4. Which of the following is not a valid mode for opening a
file?
A. r
B. a+
C. w
D. rw
44. 5. Why do you need to declare a FILE object for file
handling?
A. The FILE object is used to declare a file pointer to the file stream
B. The FILE object creates the buffer to store the file stream
C. The FILE object is a part of opening function
D. All of the reasons explained are wrong
6. What is the function of fclose() function?
A. fclose() frees the memory held by the file pointer
B. fclose() is optional
C. fclose() writes all the unsaved data
D. fclose() may avoided in some situations
45. 7. What is a C macro?
A. It is similar to function and returns a single value
B. It is a fragment of code that is given a name. when the name
appears in the code it is replaced with the code it represents.
C. A C macro is replacement of header file.
D. None of above are correct.
8. Which of the following codes are correct?
For the given statement:
A. area=PI*radius*radius;
B. PI=34;
C. area=PI*radius**2;
D. Area=pi*radius*radius;
#define PI 3.1415
int radius;