SlideShare ist ein Scribd-Unternehmen logo
1 von 124
UNIT III : File Handling and Preprocessor
Directives
By
Mr.S.Selvaraj
Asst. Professor (SRG) / CSE
Kongu Engineering College
Perundurai, Erode, Tamilnadu, India
Thanks to and Resource from : Sumitabha Das, “Computer Fundamentals and C Programming”, 1st Edition, McGraw Hill, 2018.
20CST21 – Programming and Linear Data Structures
Syllabus – Unit Wise
6/9/2021 3.1 _ File Handling Basics 2
List of Exercises
6/9/2021 3.1 _ File Handling Basics 3
Text Book and Reference Book
6/9/2021 3.1 _ File Handling Basics 4
Unit III : Contents
1. File Handling Basics
2. Text and Binary files
3. Opening and closing files
4. Detecting the End-Of-File, File pointer and file buffer
5. File read/write functions
6. Formatted functions fscanf() and fprintf()
7. Reading and writing binary files
8. Manipulating file position indicator
9. Renaming and Removing a file
10. Command line Arguments
11. Preprocessor
12. #define macros with and without arguments
13. #include directive
14. Conditional Compilation
6/9/2021 5
3.1 _ File Handling Basics
File Handling Basics
• So far, the input to the C programs is given from the
prompt / terminal.
• When a program is terminated, the entire input data is
lost.
• Storing in a file will preserve the data even if the program
terminates.
• Also to handle a large number of data, it will take a lot of
time to feed them through the terminal.
• If those data are stored in a file, then it is easy to access
them from the file using the file handling functions in C.
• In C programming, a file represents a sequence of bytes on
the disk where a group of related data is stored.
• All file handling functions are available in <stdio.h> header
file.
6/9/2021 3.1 _ File Handling Basics 6
Types of Files
• There are two types of files exists in C
Programming.
• They are:
– Text files
– Binary files
6/9/2021 3.1 _ File Handling Basics 7
Text Files
• Text files contain ASCII codes of digits, alphabetic and
symbols.
• Text files are the normal files that can be easily created
using Notepad or any simple text editors with an extension
“.txt”.
• When opening those files, it is possible to see all the
contents as plain text.
• We can easily edit or delete the contents.
• Plus and Minus of Text Files:
– They take minimum effort to maintain (+)
– Easily readable (+)
– provide least security (-)
– takes bigger storage space (-)
6/9/2021 3.1 _ File Handling Basics 8
Binary Files
• Instead of storing data in plain text, they store it
in the binary form (0's and 1's).
• Binary files usually have an extension “.bin”.
• Plus and Minus of Binary Files:
– They can hold higher amount of data (-)
– not readable easily (-)
– provides a better security than text files (+)
• For example, given the integer number 12345.
– we could store it as individual characters 1, 2, 3, 4,
and 5, using one byte for each character in text file as
6/9/2021 3.1 _ File Handling Basics 9
• 1. Opening a New/Existing file
• 2. Writing data into a file
• 3. Reading data from the file
• 4. Closing a file
Operations on Files
6/9/2021 10
3.1 _ File Handling Basics
Opening a New/Existing file
• When working with files, it is mandatory to declare a
pointer of type FILE as below:
• The FILE is a structure data type defined in <stdio.h>.
• This declaration is needed for communication between
the file and program.
• A file should be opened before any operation is being
performed on it.
6/9/2021 3.1 _ File Handling Basics 11
Opening a New/Existing file
• The syntax of fopen() is given by,
• In the above format, the arguments “path”
and “mode” are strings.
• The fopen()
– returns a pointer to FILE structure on success
– else it returns NULL.
6/9/2021 3.1 _ File Handling Basics 12
Opening a New/Existing file
• Every file on the disk has a name known as
filename.
• The filename can be specified as either
absolute path or relative path.
• In the absolute path, the complete location of
the file is given whereas only partial path is
mentioned in the relative path.
6/9/2021 3.1 _ File Handling Basics 13
Opening a New/Existing file
• The file mode specifies the kind of operation performed on the
file.
• The various file modes are given in the following table:
6/9/2021 3.1 _ File Handling Basics 14
Opening a New/Existing file
6/9/2021 3.1 _ File Handling Basics 15
Create a New File using fopen()
• To create a new text file “file1.txt”, we can open
the file in write mode(“w”) as given below:
• In the above example, suppose the file “file1.txt”
already exist in the location E:CPrograms.
• The fopen() removes all the contents from the
file “file1.txt” and creates a new empty file
named “file1.txt”.
• If “file1.txt”does not exist, new empty file
named “file1.txt” is created.
6/9/2021 3.1 _ File Handling Basics 16
Read file contents
• To read the contents of the text file “sample.txt”, we
can open the file in read mode(“r”) as given below:
• In the above example, suppose the text file
“sample.txt” exists in the current working directory.
• The function fopen() opens the file for reading in text
mode.
• The reading mode only allows us to read the file, we
cannot write into the file.
6/9/2021 3.1 _ File Handling Basics 17
Difference between Append and Write Mode
• Both write (w) mode and append (a) mode are used to
write data into a file.
• In both the modes, new file is created if it doesn't exist
already.
• The only difference is, when a file is opened in the
write mode, the file is reset, resulting in deletion of
any data already present in the file.
• While in append mode this will not happen.
• Append mode is used to append or add data to the
existing data of file (if any).
• Hence, when a file is opened in append (a) mode, the
file pointer/cursor is positioned at the end of the file.
6/9/2021 3.1 _ File Handling Basics 18
Example 1
6/9/2021 3.1 _ File Handling Basics 19
Example 2:
char filename[80];
FILE *fp;
printf(“Enter the filename to be opened”);
gets(filename);
fp = fopen(filename,“w”);
6/9/2021 20
3.1 _ File Handling Basics
Example 2
• The file should be closed after performing read/write
operation.
• Closing of a file is performed using the function
fclose().
• Closing a file frees the file pointer (file pointer is
disconnected from a file) and associated buffers.
• The fclose() will close the file specified by the fptr
whereas the fcloseall() closes all the files that are
already opened.
• The fclose() function
– returns 0 if close operation is successful or
– returns EOF if an error was encountered.
Closing a File
6/9/2021 21
3.1 _ File Handling Basics
Detecting the End-of-File (EOF)
• While performing read and write operations
on files, we do not know exactly how long the
file is.
• Usually, we read data from the beginning to
the end of the file.
• To identify the reach of end-of-file (EOF),
there are two ways available.
6/9/2021 3.1 _ File Handling Basics 22
Way 1
• While reading the file in text mode by character
at a time, we can compare the character that has
been read with EOF, which is a symbolic constant
defined in stdio.h whose value is set to -1.
• The following code snippet does that,
6/9/2021 3.1 _ File Handling Basics 23
Way 2
• The other way is the use of feof( ) function defined in
stdio.h.
• The syntax of feof( ) is given by:
• The function returns 0 (false) when the end of the file
has not been reached and a non-zero value (true) if
the EOF has been reached.
• A simple code snippet using feof( ) is given as
6/9/2021 3.1 _ File Handling Basics 24
• fopen has two important consequences
– creation of a file pointer and file buffer
• File pointer is a variable that points to a structure
typedef to FILE.
• FILE contains the following information related to
the opened file
– The mode of opening.
– The location of the file buffer.
– The file position indicator.
– Whether EOF or any errors have been encountered on
reading or writing.
• File position indicator also called file offset pointer,
plays important role in input/output operations
Detecting the file pointer and file buffer
6/9/2021 25
3.1 _ File Handling Basics
• When a file is read with fgetc, data is first sent
from disk to the buffer.
Detecting the file pointer and file buffer
6/9/2021 26
3.1 _ File Handling Basics
Example 3:
FILE *fp;
fp = fopen(“data.dat”,“r”);
if(fp == NULL)
{
printf(“Can not open data.datn”);
exit(1);
}
Or
FILE *fp;
if((fp = fopen(“data.dat”, “r”)) ==NULL)
{
printf(“Can not open data.datn”);
exit(1);
}
6/9/2021 27
3.1 _ File Handling Basics
Detecting File Pointer
Thank you
6/9/2021 3.1 _ File Handling Basics 28
UNIT III : File Handling and Preprocessor
Directives
By
Mr.S.Selvaraj
Asst. Professor (SRG) / CSE
Kongu Engineering College
Perundurai, Erode, Tamilnadu, India
Thanks to and Resource from : Sumitabha Das, “Computer Fundamentals and C Programming”, 1st Edition, McGraw Hill, 2018.
20CST21 – Programming and Linear Data Structures
Unit III : Contents
1. File Handling Basics
2. Text and Binary files
3. Opening and closing files
4. Detecting the End-Of-File, File pointer and file buffer
5. File read/write functions
6. Formatted functions fscanf() and fprintf()
7. Reading and writing binary files
8. Manipulating file position indicator
9. Renaming and Removing a file
10. Command line Arguments
11. Preprocessor
12. #define macros with and without arguments
13. #include directive
14. Conditional Compilation
6/9/2021 30
3.2 _ Reading and Writing Functions in Files
Input and Output Operations
• A C program can read data from the keyboard and
writes data into the monitor.
• Similarly, it can read and write from/into the file as
shown in the diagram.
6/9/2021 3.2 _ Reading and Writing Functions in Files 31
Input and Output Operations
• A number of functions are available for
performing operations on files.
• They are classified as formatted File I/O and
unformatted File I/O functions.
• The formatted functions deal with all kind of
data whereas the unformatted functions deal
only character data type.
• Different functions are also available for
handling text as well as binary files.
6/9/2021 3.2 _ Reading and Writing Functions in Files 32
List of read/input functions
• To perform read operations the following
functions are used.
– fgetc ( )
– fgets ( )
– fscanf ( )
– fread ( )
6/9/2021 3.2 _ Reading and Writing Functions in Files 33
List of write/output functions
• To perform read operations the following
functions are used.
– fputc ( )
– fputs ( )
– fprintf ( )
– fwrite ( )
6/9/2021 3.2 _ Reading and Writing Functions in Files 34
• Character-oriented functions (fgetc and fputc)
• Line-oriented functions (fgets and fputs)
• Formatted functions (fscanf and fprintf)
• Array- and structure-oriented functions (fread
and fwrite)
• All the functions use the file pointer as
argument and work with any file including
stdin, stdout and stderr.
List of Read/Write functions
6/9/2021 35
3.2 _ Reading and Writing Functions in Files
Reading and Writing to a text file using fgetc () and fputc ()
• fgetc () reads the content of the file character by
character.
• After reading a character from the file, fgetc() function
moves the file pointer to next character in the file.
• The fgetc () function returns the next character from
the file specified.
• It returns EOF if end-of-file is reached or error
occurred.
6/9/2021 3.2 _ Reading and Writing Functions in Files 36
Example 1
• Assume there is a text file “file1.txt” with the
content “Hello World!” . Write the C program
to read that file one character at a time using
fgetc() function and display it on the monitor.
6/9/2021 3.2 _ Reading and Writing Functions in Files 37
6/9/2021 3.2 _ Reading and Writing Functions in Files 38
fputc ( ) function
• The function fputc ( ) writes a character to the
specified file and automatically advances the file
pointer to the next position in the file.
– On success, the written character is returned by the
function.
– If pointer is at end of file or if an error occurs EOF file
is returned by this function.
• Syntax:
– char − This is the character to be written.
– fptr − This is the pointer to a specified file that
indicates where the character is to be written.
6/9/2021 3.2 _ Reading and Writing Functions in Files 39
Example 2
• Write a c program to write the string
“Engineers create the World” in the file
sample.txt using fputc() function.
6/9/2021 3.2 _ Reading and Writing Functions in Files 40
6/9/2021 3.2 _ Reading and Writing Functions in Files 41
Reading and Writing to a text file using fgets () and fputs ()
• The function fgets() is used to read a file line by line.
– str − This is the pointer to an array of characters where
the string read is stored.
– size − This is the maximum number of characters to be
read (including terminating character “0”). Usually, the
length of the array “str” is used.
– fptr − This is the pointer that identifies the file where
characters are read from.
6/9/2021 3.2 _ Reading and Writing Functions in Files 42
Reading and Writing to a text file using fgets () and fputs ()
• fgets ( ) reads a line from the specified file and stores
it into the string pointed to by str.
– It stops when (size-1) characters are read or
– the newline character is read, or
– the end-of-file is reached, whichever comes first.
• While all the characters are read without any error, a
null (“ 0” ) character is appended to the end of the
string.
• On success, fgets () returns the same str parameter.
• If end-of-file is encountered or an error occurred, a
NULL value is returned.
6/9/2021 3.2 _ Reading and Writing Functions in Files 43
Example 3
• Again consider the text file “file1.txt”. Now,
write a C program to read the file using fgets()
function and read 4 characters at a time and
those are displayed in the monitor.
6/9/2021 3.2 _ Reading and Writing Functions in Files 44
6/9/2021 3.2 _ Reading and Writing Functions in Files 45
fputs ( ) function
• This function is used to write a string into the file.
• It has two arguments,
– pointer to string and
– file pointer.
• It writes a null-terminated string to the file.
• The null character is not written to the file.
• On success, fputs( ) returns Non-negative value.
• On error, it returns EOF or Negative value.
• str − This is an array containing a string (terminated by
“0”) to be written into a file.
• fptr − This is the pointer to a specified file that
identifies the stream where the string is to be written.
6/9/2021 3.2 _ Reading and Writing Functions in Files 46
Example 4
• Write a C program to write 5 strings into the
file sample.txt using fputs() function.
6/9/2021 3.2 _ Reading and Writing Functions in Files 47
6/9/2021 3.2 _ Reading and Writing Functions in Files 48
Reading and Writing to a text file using fscanf() and fprintf ()
• For reading and writing to a text file, we use
the functions fscanf() and fprintf() .
• They are just the file versions of scanf()
and printf().
• The only difference is that fscanf() and fprint()
expects a pointer to the structure FILE.
• Other functions like fgetchar(), fputc() etc. can
be used in a similar way.
6/9/2021 3.2 _ Reading and Writing Functions in Files 49
fscanf ( ) function
• The functions fgetc ( ) and fgets ( ) are used for
reading only character data.
• But, fscanf ( ) can read different types of data
such as int, float, char, etc., from the given file.
• On success, this function returns the number of
input items successfully matched and assigned
to argument specified.
• On failure, it returns EOF.
6/9/2021 3.2 _ Reading and Writing Functions in Files 50
fscanf ( ) function
• The parameters used in the fscanf() are:
– fptr − This is the pointer that identifies the file where
characters are read from.
– format-string – This is a string which controls the
interpretation of the argument list. A format
specification causes the fscanf() function to read and
convert characters in the input into values of a
specified type.
– argument-list - The value read from the file based on
format-string is assigned to an argument in the
argument list.
6/9/2021 3.2 _ Reading and Writing Functions in Files 51
Example 5
• Write a C program to Read the integer
number from a file sample.txt using fscanf()
function.
6/9/2021 3.2 _ Reading and Writing Functions in Files 52
6/9/2021 3.2 _ Reading and Writing Functions in Files 53
fprintf () function
• Like fscanf( ), the function fprintf( ) handles
different types of data.
• It can be used for writing formatted data into
the file.
• On success, fprintf( ) returns the total number
of bytes written to the file.
• On error, it returns EOF.
6/9/2021 3.2 _ Reading and Writing Functions in Files 54
Example 6
• Write a C program to Read the details about n
students from the user and write those
information into the file sample.txt using
fprintf() function.
6/9/2021 3.2 _ Reading and Writing Functions in Files 55
6/9/2021 3.2 _ Reading and Writing Functions in Files 56
Reading and Writing to a text file using fread() and fwrite ()
• The functions fgetc(), fgets() and fscanf() are used to
read data from text files.
• The function fread() is used to get data from binary
files.
• In binary files, information is stored in the form of
binary and it can be read directly into memory with no
need of any processing to interpret it.
• Hence, handling of files in binary mode is significantly
faster than text mode.
• On success, fread() returns the number of items read
from the file.
• On error or EOF, it returns a number less than “n”.
6/9/2021 3.2 _ Reading and Writing Functions in Files 57
fread() function
• Syntax:
– ptr – It is the starting address of the memory block where
data is to be read.
– size – Item size in bytes.
– n- It indicates the maximum number of items read from
the file
– fptr –It specifies the pointer to file from where the data
has to be read.
• The following code snippet discuss about the different
ways in which fread() can be used.
6/9/2021 3.2 _ Reading and Writing Functions in Files 58
6/9/2021 3.2 _ Reading and Writing Functions in Files 59
fwrite() function
• fwrite( ) function is used to write binary data into the
file.
• It accepts the same arguments as fread( ).
• Syntax:
• On success, it returns the number of items successfully
written to the file.
• On error, it returns a number less than n.
• The following code snippets show the usage of fwrite()
function in handling different data.
6/9/2021 3.2 _ Reading and Writing Functions in Files 60
6/9/2021 3.2 _ Reading and Writing Functions in Files 61
The first fwrite( ) function writes only
the first three elements of the array
into the file. But, the second one
writes the last three elements of the
array into the file.
Example 7
• Write a C Program to Write the details about 3
students into the file sample.txt using fwrite()
function.
6/9/2021 3.2 _ Reading and Writing Functions in Files 62
6/9/2021 3.2 _ Reading and Writing Functions in Files 63
6/9/2021 3.2 _ Reading and Writing Functions in Files 64
Practice Problem 1
• Get a line of text from the user and write it
into a file named „sample.txt‟. Read the
contents from the file and display it on the
monitor. Use fgetc() and fputc() functions to
manipulate the file.
6/9/2021 3.2 _ Reading and Writing Functions in Files 65
Practice Problem 2
• Write a program to copy the content of one
file into another one. Get the source and
target file names from the user.
6/9/2021 3.2 _ Reading and Writing Functions in Files 66
Practice Problem 3
• Write a C program to compare two files for
checking whether two files contains the same
content or not.
6/9/2021 3.2 _ Reading and Writing Functions in Files 67
Practice Problem 5
• Write a program to add some content at the
end to the existing file.
6/9/2021 3.2 _ Reading and Writing Functions in Files 68
Practice Problem 5
• Write a program to get the details (such as
Name, Roll No, five subjects marks ) of N
students and find the Total mark and Rank for
each student. Write Name, RollNo, Total mark
and Rank for each student into a file named
“studentdb.txt” using formatted file I/O
functions and also display these details in
tabular format.
6/9/2021 3.2 _ Reading and Writing Functions in Files 69
Practice Problem 6
• Write a program to create and manage a student
database with the listed operations
1. Add a new student by giving his/her roll number,
name and average mark.
2. Display the details about a student for a given roll
number
3. Display the details of all students in the database
4. Update the average mark of a student for a given roll
number
5. Delete a student record if roll number is given
6/9/2021 3.2 _ Reading and Writing Functions in Files 70
Thank you
6/9/2021 3.2 _ Reading and Writing Functions in Files 71
UNIT III : File Handling and Preprocessor
Directives
By
Mr.S.Selvaraj
Asst. Professor (SRG) / CSE
Kongu Engineering College
Perundurai, Erode, Tamilnadu, India
Thanks to and Resource from : Sumitabha Das, “Computer Fundamentals and C Programming”, 1st Edition, McGraw Hill, 2018.
20CST21 – Programming and Linear Data Structures
Unit III : Contents
1. File Handling Basics
2. Text and Binary files
3. Opening and closing files
4. Detecting the End-Of-File, File pointer and file buffer
5. File read/write functions
6. Formatted functions fscanf() and fprintf()
7. Reading and writing binary files
8. Manipulating file position indicator
9. Renaming and Removing a file
10. Command line Arguments
11. Preprocessor
12. #define macros with and without arguments
13. #include directive
14. Conditional Compilation
6/9/2021 73
3.3 _ Manipulating, Removing and
Renaming a File
Sequential Access and Random Access Files
• Based on the method of accessing the data stored, files
can be classified into two types.
– Sequential access file
– Random access file
• In the sequential access file, data is kept in sequential
order. To access the last record of the file, we need to
read all records preceding to that record.
– Hence, it takes more time.
• But, in random access files data can be read and
modified at any random position. Unlike sequential
access, the any record can be read directly.
– Hence, it takes less time.
6/9/2021
3.3 _ Manipulating, Removing and
Renaming a File
74
Difference b/w Sequential and Random Access Files
6/9/2021
3.3 _ Manipulating, Removing and
Renaming a File
75
Random Accessing in Files
• To achieve random accessing in files, the
following functions are used
– fseek()
– ftell()
– rewind()
6/9/2021
3.3 _ Manipulating, Removing and
Renaming a File
76
Manipulating file position indicator using
fseek( ) function
• If there are many records inside a file and
need to access a record at a specific position
fseek( ) is used.
• As the name suggests, fseek() moves file
pointer associated with a given file to a
specific position.
• The fseek() function returns 0 if the move is
successful, else it returns a non-zero value.
6/9/2021
3.3 _ Manipulating, Removing and
Renaming a File
77
fseek() function
• fptr - It is the pointer to the file.
• Offset - It indicates the number of bytes to move from
the position specified by the third argument. The
positive value of offset makes the move in the forward
direction whereas the negative value in the
backward(reverse) direction.
• Position - It defines the point with respect to which the
file pointer needs to be moved. It has three values:
6/9/2021
3.3 _ Manipulating, Removing and
Renaming a File
78
Example
6/9/2021
3.3 _ Manipulating, Removing and
Renaming a File
79
ftell( ) function
• The ftell() function is used to return the
position of file pointer in the file with respect
to starting of the file.
6/9/2021
3.3 _ Manipulating, Removing and
Renaming a File
80
Example
• The value of p is 12 which also indicate the
size of the file.
6/9/2021
3.3 _ Manipulating, Removing and
Renaming a File
81
rewind( ) function
• The rewind function sets the file position to
the beginning of the file.
• The rewind( ) is equivalent to
– fseek (fptr, 0, SEEK_SET).
6/9/2021
3.3 _ Manipulating, Removing and
Renaming a File
82
Example
• Write a program to reverse the contents of
the text file using fseek() function.
6/9/2021
3.3 _ Manipulating, Removing and
Renaming a File
83
6/9/2021
3.3 _ Manipulating, Removing and
Renaming a File
84
Removing a file : remove ( ) function
• The remove function can be used to delete a
file that is not opened already.
• The function returns zero if file is deleted
successfully, else returns a non-zero value.
6/9/2021
3.3 _ Manipulating, Removing and
Renaming a File
85
Renaming a file: rename ( ) function
• The function rename() is used to change the
name of the file
• i.e. from old_name to new_name without
changing the content present in the file.
• Syntax:
– If the file is renamed successfully, zero is returned.
– On failure, a nonzero value is returned.
6/9/2021
3.3 _ Manipulating, Removing and
Renaming a File
86
Thank you
6/9/2021
3.3 _ Manipulating, Removing and
Renaming a File
87
UNIT III : File Handling and Preprocessor
Directives
By
Mr.S.Selvaraj
Asst. Professor (SRG) / CSE
Kongu Engineering College
Perundurai, Erode, Tamilnadu, India
Thanks to and Resource from : Sumitabha Das, “Computer Fundamentals and C Programming”, 1st Edition, McGraw Hill, 2018.
20CST21 – Programming and Linear Data Structures
Unit III : Contents
1. File Handling Basics
2. Text and Binary files
3. Opening and closing files
4. Detecting the End-Of-File, File pointer and file buffer
5. File read/write functions
6. Formatted functions fscanf() and fprintf()
7. Reading and writing binary files
8. Manipulating file position indicator
9. Renaming and Removing a file
10. Command line Arguments
11. Preprocessor
12. #define macros with and without arguments
13. #include directive
14. Conditional Compilation
6/9/2021 89
3.4 _ Command Line Arguments
Command-line Arguments
• Command line argument is a parameter
supplied to the program when it is invoked.
• It is possible to pass values from the
command line to the C programs when they
are executed.
• These values are called command line
arguments.
• Executable code of the program should be
compiled from DOS prompt.
6/9/2021 3.4 _ Command Line Arguments 90
Command-line Arguments
• The command line arguments are handled by
arguments given in main() function.
• The main() can be defined as,
6/9/2021 3.4 _ Command Line Arguments 91
Command-line Arguments
• The first argument argc refers to the number
of arguments passed to main().
• and the second argument argv[] is an array of
character pointers which points to each
argument passed to the main().
6/9/2021 3.4 _ Command Line Arguments 92
Command-line Arguments
• The array argv contains the elements
– argv[0] holds the name of the program itself.
– argv[1] is a pointer to the first command line argument
supplied
– argv[2] is a pointer to the second command line argument
supplied
– …….
– argv[argc-1] is a pointer to the last command line
argument supplied to the program.
• If no argument is supplied to the program, the
parameter argc will be set to one.
• if one argument is passed then argc is set to 2.
6/9/2021 3.4 _ Command Line Arguments 93
Command-line Arguments
• Steps to be followed to execute program using
Command Line Argument inside Borland C Compiler :
– Step 1 : Enter a Program and compile it.
– Step 2 : Open File menu inside Borland C.
– Step 3 : Click on DOS Shell.
– Step 4 : In the Command Prompt type the filename
(Program name without any extension) with the
arguments and press Enter Key using the format “filename
value 1 value 2 ..... Value m” . Program will be executed
with the given arguments and output is generated.
– Step 5 : Type “exit” command to return to Borland C
6/9/2021 3.4 _ Command Line Arguments 94
Example 1
• Write an example program to checks if there
is any argument supplied from the command
line and display these arguments.
6/9/2021 3.4 _ Command Line Arguments 95
6/9/2021 3.4 _ Command Line Arguments 96
Example 2
• Write a program to add all the numbers given
as Command Line Arguments.
6/9/2021 3.4 _ Command Line Arguments 97
6/9/2021 3.4 _ Command Line Arguments 98
Example 3
• Write a program to copy one file into another
file using command line argument.
6/9/2021 3.4 _ Command Line Arguments 99
6/9/2021 3.4 _ Command Line Arguments 100
6/9/2021 3.4 _ Command Line Arguments 101
6/9/2021 3.4 _ Command Line Arguments 102
Problem 1
6/9/2021 3.4 _ Command Line Arguments 103
Thank you
6/9/2021 3.4 _ Command Line Arguments 104
UNIT III : File Handling and Preprocessor
Directives
By
Mr.S.Selvaraj
Asst. Professor (SRG) / CSE
Kongu Engineering College
Perundurai, Erode, Tamilnadu, India
Thanks to and Resource from : Sumitabha Das, “Computer Fundamentals and C Programming”, 1st Edition, McGraw Hill, 2018.
20CST21 – Programming and Linear Data Structures
Unit III : Contents
1. File Handling Basics
2. Text and Binary files
3. Opening and closing files
4. Detecting the End-Of-File, File pointer and file buffer
5. File read/write functions
6. Formatted functions fscanf() and fprintf()
7. Reading and writing binary files
8. Manipulating file position indicator
9. Renaming and Removing a file
10. Command line Arguments
11. Preprocessor
12. #define macros with and without arguments
13. #include directive
14. Conditional Compilation
6/9/2021 106
3.5 _ Preprocessor
Preprocessor
• As the name suggests preprocessors are programs that
processes the source code before compilation as shown in
figure.
• Preprocessor provides preprocessor directives which tell
the compiler to preprocess the source code before the
complier starts its work.
• All the preprocessor directives begin with a “#” (hash)
symbol.
• The preprocessor directives can be placed anywhere in the
program.
6/9/2021 3.5 _ Preprocessor 107
Types of Preprocessor directives
• There are three different types of
preprocessor directives :
– Macros
– File Inclusion
– Conditional Compilation
6/9/2021 3.5 _ Preprocessor 108
Macros
• Macros are piece of code in a program which
is assigned with some name.
• Whenever this name is encountered by the
compiler the compiler replaces the name with
the actual piece of code.
• The “#define” directive is used to define a
macro.
• There are two types of macros –
– one which takes the argument and
– another which does not take any argument.
6/9/2021 3.5 _ Preprocessor 109
Difference between Macros and Functions
6/9/2021 3.5 _ Preprocessor 110
Macros without argument
• Every occurrences of macro name is replaced
with the actual piece of code by the compiler.
• This kind of macros usually used to give symbolic
names to numeric constants.
• There is no semi-colon(“;‟) is needed at the end
of a macro definition.
6/9/2021 3.5 _ Preprocessor 111
Example
6/9/2021 3.5 _ Preprocessor 112
Macros with arguments
• It is also possible to pass arguments to
macros.
• Macro with arguments works similarly as
functions.
6/9/2021 3.5 _ Preprocessor 113
Example
6/9/2021 3.5 _ Preprocessor 114
Nesting of macros
• macro may be used in the definition of
another macro. This is known as nesting of
macros.
6/9/2021 3.5 _ Preprocessor 115
Example
6/9/2021 3.5 _ Preprocessor 116
File Inclusion
• The #include preprocessor is used to include
header files to a C program.
• This directive instructs the compiler to include a
specified file to the C program.
• Here, "stdio.h" is a header file.
• The #include preprocessor directive replaces the
above line with the contents of stdio.h header
file which contain function and macro definitions.
6/9/2021 3.5 _ Preprocessor 117
File Inclusion
• Rules for file inclusion are:
– 1. File inclusive Directives are used to include
standard or user define header file inside C Program.
– 2. File inclusive directory checks included header file
inside same directory (if path is not mentioned).
– 3. File inclusive directives begins with #include
– 4. If Path is mentioned then it will include the header
file present in the location specified by that path.
– 5. Instead of using triangular brackets we use “Double
Quote” for inclusion of user defined header file.
6/9/2021 3.5 _ Preprocessor 118
Including Standard Header Files
6/9/2021 3.5 _ Preprocessor 119
Including User Defined Header Files
6/9/2021 3.5 _ Preprocessor 120
Conditional Compilation
• Conditional compilation is the process of selecting
which code to compile and which code to not compile
similar to the #if / #else / #endif in C and C++.
• Conditional Compilation directives helps to include or
skip a specific block of code in the source code based
on some conditions.
• This can be done with the help of “ifdef” and “endif”
preprocessing directives.
• If the macro in #ifdef is defined, then the block of
statements will be executed normally. But, if it is not
defined, then the compiler will simply skip that block
of statements.
6/9/2021 3.5 _ Preprocessor 121
Conditional Compilation
6/9/2021 3.5 _ Preprocessor 122
Example
6/9/2021 3.5 _ Preprocessor 123
Thank you
6/9/2021 3.5 _ Preprocessor 124

Weitere ähnliche Inhalte

Was ist angesagt?

Mesics lecture files in 'c'
Mesics lecture   files in 'c'Mesics lecture   files in 'c'
Mesics lecture files in 'c'eShikshak
 
Data file handling in c++
Data file handling in c++Data file handling in c++
Data file handling in c++Vineeta Garg
 
python file handling
python file handlingpython file handling
python file handlingjhona2z
 
File Handling In C++(OOPs))
File Handling In C++(OOPs))File Handling In C++(OOPs))
File Handling In C++(OOPs))Papu Kumar
 
File Handling Python
File Handling PythonFile Handling Python
File Handling PythonAkhil Kaushik
 
Report blocking ,management of files in secondry memory , static vs dynamic a...
Report blocking ,management of files in secondry memory , static vs dynamic a...Report blocking ,management of files in secondry memory , static vs dynamic a...
Report blocking ,management of files in secondry memory , static vs dynamic a...NoorMustafaSoomro
 
basics of file handling
basics of file handlingbasics of file handling
basics of file handlingpinkpreet_kaur
 
C UNIT-5 PREPARED BY M V BRAHMANANDA REDDY
C UNIT-5 PREPARED BY M V BRAHMANANDA REDDYC UNIT-5 PREPARED BY M V BRAHMANANDA REDDY
C UNIT-5 PREPARED BY M V BRAHMANANDA REDDYRajeshkumar Reddy
 
File handling in vb.net
File handling in vb.netFile handling in vb.net
File handling in vb.netEverywhere
 
File Reconstruction in Digital Forensic
File Reconstruction in Digital ForensicFile Reconstruction in Digital Forensic
File Reconstruction in Digital ForensicTELKOMNIKA JOURNAL
 
Data and File Structure Lecture Notes
Data and File Structure Lecture NotesData and File Structure Lecture Notes
Data and File Structure Lecture NotesFellowBuddy.com
 
Stream classes in C++
Stream classes in C++Stream classes in C++
Stream classes in C++Shyam Gupta
 
08. handling file streams
08. handling file streams08. handling file streams
08. handling file streamsHaresh Jaiswal
 

Was ist angesagt? (20)

Mesics lecture files in 'c'
Mesics lecture   files in 'c'Mesics lecture   files in 'c'
Mesics lecture files in 'c'
 
Data file handling in c++
Data file handling in c++Data file handling in c++
Data file handling in c++
 
Python file handling
Python file handlingPython file handling
Python file handling
 
python file handling
python file handlingpython file handling
python file handling
 
File Handling In C++(OOPs))
File Handling In C++(OOPs))File Handling In C++(OOPs))
File Handling In C++(OOPs))
 
File Handling Python
File Handling PythonFile Handling Python
File Handling Python
 
File handling in c++
File handling in c++File handling in c++
File handling in c++
 
File mangement
File mangementFile mangement
File mangement
 
Report blocking ,management of files in secondry memory , static vs dynamic a...
Report blocking ,management of files in secondry memory , static vs dynamic a...Report blocking ,management of files in secondry memory , static vs dynamic a...
Report blocking ,management of files in secondry memory , static vs dynamic a...
 
Files nts
Files ntsFiles nts
Files nts
 
basics of file handling
basics of file handlingbasics of file handling
basics of file handling
 
Programming in C
Programming in CProgramming in C
Programming in C
 
C UNIT-5 PREPARED BY M V BRAHMANANDA REDDY
C UNIT-5 PREPARED BY M V BRAHMANANDA REDDYC UNIT-5 PREPARED BY M V BRAHMANANDA REDDY
C UNIT-5 PREPARED BY M V BRAHMANANDA REDDY
 
File handling
File handlingFile handling
File handling
 
File handling in vb.net
File handling in vb.netFile handling in vb.net
File handling in vb.net
 
File Reconstruction in Digital Forensic
File Reconstruction in Digital ForensicFile Reconstruction in Digital Forensic
File Reconstruction in Digital Forensic
 
File handling
File handlingFile handling
File handling
 
Data and File Structure Lecture Notes
Data and File Structure Lecture NotesData and File Structure Lecture Notes
Data and File Structure Lecture Notes
 
Stream classes in C++
Stream classes in C++Stream classes in C++
Stream classes in C++
 
08. handling file streams
08. handling file streams08. handling file streams
08. handling file streams
 

Ähnlich wie File Handling and Preprocessor Directives

Ähnlich wie File Handling and Preprocessor Directives (20)

File Handling
File HandlingFile Handling
File Handling
 
File Handling
File HandlingFile Handling
File Handling
 
INput output stream in ccP Full Detail.pptx
INput output stream in ccP Full Detail.pptxINput output stream in ccP Full Detail.pptx
INput output stream in ccP Full Detail.pptx
 
File Handling.pptx
File Handling.pptxFile Handling.pptx
File Handling.pptx
 
File handling.pptx
File handling.pptxFile handling.pptx
File handling.pptx
 
Unit-VI.pptx
Unit-VI.pptxUnit-VI.pptx
Unit-VI.pptx
 
File Management and manipulation in C++ Programming
File Management and manipulation in C++ ProgrammingFile Management and manipulation in C++ Programming
File Management and manipulation in C++ Programming
 
C- language Lecture 8
C- language Lecture 8C- language Lecture 8
C- language Lecture 8
 
Chapter 08 data file handling
Chapter 08 data file handlingChapter 08 data file handling
Chapter 08 data file handling
 
File management in C++
File management in C++File management in C++
File management in C++
 
File management
File managementFile management
File management
 
File handling in C hhsjsjshsjjsjsjs.pptx
File handling in C hhsjsjshsjjsjsjs.pptxFile handling in C hhsjsjshsjjsjsjs.pptx
File handling in C hhsjsjshsjjsjsjs.pptx
 
VIT351 Software Development VI Unit5
VIT351 Software Development VI Unit5VIT351 Software Development VI Unit5
VIT351 Software Development VI Unit5
 
DFH PDF-converted.pptx
DFH PDF-converted.pptxDFH PDF-converted.pptx
DFH PDF-converted.pptx
 
EASY UNDERSTANDING OF FILES IN C LANGUAGE.pdf
EASY UNDERSTANDING OF FILES IN C LANGUAGE.pdfEASY UNDERSTANDING OF FILES IN C LANGUAGE.pdf
EASY UNDERSTANDING OF FILES IN C LANGUAGE.pdf
 
Unit V.pptx
Unit V.pptxUnit V.pptx
Unit V.pptx
 
File handing in C
File handing in CFile handing in C
File handing in C
 
File handling C program
File handling C programFile handling C program
File handling C program
 
UNIT 5.pptx
UNIT 5.pptxUNIT 5.pptx
UNIT 5.pptx
 
file handling.pdf
file handling.pdffile handling.pdf
file handling.pdf
 

Mehr von Selvaraj Seerangan

Unit 2,3,4 _ Internet of Things A Hands-On Approach (Arshdeep Bahga, Vijay Ma...
Unit 2,3,4 _ Internet of Things A Hands-On Approach (Arshdeep Bahga, Vijay Ma...Unit 2,3,4 _ Internet of Things A Hands-On Approach (Arshdeep Bahga, Vijay Ma...
Unit 2,3,4 _ Internet of Things A Hands-On Approach (Arshdeep Bahga, Vijay Ma...Selvaraj Seerangan
 
END SEM _ Design Thinking _ 16 Templates.pptx
END SEM _ Design Thinking _ 16 Templates.pptxEND SEM _ Design Thinking _ 16 Templates.pptx
END SEM _ Design Thinking _ 16 Templates.pptxSelvaraj Seerangan
 
Design Thinking _ Complete Templates.pptx
Design Thinking _ Complete Templates.pptxDesign Thinking _ Complete Templates.pptx
Design Thinking _ Complete Templates.pptxSelvaraj Seerangan
 
CAT 3 _ List of Templates.pptx
CAT 3 _ List of Templates.pptxCAT 3 _ List of Templates.pptx
CAT 3 _ List of Templates.pptxSelvaraj Seerangan
 
[PPT] _ Unit 3 _ Experiment.pptx
[PPT] _ Unit 3 _ Experiment.pptx[PPT] _ Unit 3 _ Experiment.pptx
[PPT] _ Unit 3 _ Experiment.pptxSelvaraj Seerangan
 
CAT 2 _ List of Templates.pptx
CAT 2 _ List of Templates.pptxCAT 2 _ List of Templates.pptx
CAT 2 _ List of Templates.pptxSelvaraj Seerangan
 
Design Thinking - Empathize Phase
Design Thinking - Empathize PhaseDesign Thinking - Empathize Phase
Design Thinking - Empathize PhaseSelvaraj Seerangan
 
18CSL51 - Network Lab Manual.pdf
18CSL51 - Network Lab Manual.pdf18CSL51 - Network Lab Manual.pdf
18CSL51 - Network Lab Manual.pdfSelvaraj Seerangan
 
CAT 1 _ List of Templates.pptx
CAT 1 _ List of Templates.pptxCAT 1 _ List of Templates.pptx
CAT 1 _ List of Templates.pptxSelvaraj Seerangan
 
[PPT] _ UNIT 1 _ COMPLETE.pptx
[PPT] _ UNIT 1 _ COMPLETE.pptx[PPT] _ UNIT 1 _ COMPLETE.pptx
[PPT] _ UNIT 1 _ COMPLETE.pptxSelvaraj Seerangan
 
[PPT] _ Unit 2 _ 9.0 _ Domain Specific IoT _Home Automation.pdf
[PPT] _ Unit 2 _ 9.0 _ Domain Specific IoT _Home Automation.pdf[PPT] _ Unit 2 _ 9.0 _ Domain Specific IoT _Home Automation.pdf
[PPT] _ Unit 2 _ 9.0 _ Domain Specific IoT _Home Automation.pdfSelvaraj Seerangan
 

Mehr von Selvaraj Seerangan (20)

Unit 2,3,4 _ Internet of Things A Hands-On Approach (Arshdeep Bahga, Vijay Ma...
Unit 2,3,4 _ Internet of Things A Hands-On Approach (Arshdeep Bahga, Vijay Ma...Unit 2,3,4 _ Internet of Things A Hands-On Approach (Arshdeep Bahga, Vijay Ma...
Unit 2,3,4 _ Internet of Things A Hands-On Approach (Arshdeep Bahga, Vijay Ma...
 
Unit 5 _ Fog Computing .pdf
Unit 5 _ Fog Computing .pdfUnit 5 _ Fog Computing .pdf
Unit 5 _ Fog Computing .pdf
 
CAT III Answer Key.pdf
CAT III Answer Key.pdfCAT III Answer Key.pdf
CAT III Answer Key.pdf
 
END SEM _ Design Thinking _ 16 Templates.pptx
END SEM _ Design Thinking _ 16 Templates.pptxEND SEM _ Design Thinking _ 16 Templates.pptx
END SEM _ Design Thinking _ 16 Templates.pptx
 
Design Thinking _ Complete Templates.pptx
Design Thinking _ Complete Templates.pptxDesign Thinking _ Complete Templates.pptx
Design Thinking _ Complete Templates.pptx
 
CAT 3 _ List of Templates.pptx
CAT 3 _ List of Templates.pptxCAT 3 _ List of Templates.pptx
CAT 3 _ List of Templates.pptx
 
[PPT] _ Unit 5 _ Evolve.pptx
[PPT] _ Unit 5 _ Evolve.pptx[PPT] _ Unit 5 _ Evolve.pptx
[PPT] _ Unit 5 _ Evolve.pptx
 
[PPT] _ Unit 4 _ Engage.pptx
[PPT] _ Unit 4 _ Engage.pptx[PPT] _ Unit 4 _ Engage.pptx
[PPT] _ Unit 4 _ Engage.pptx
 
[PPT] _ Unit 3 _ Experiment.pptx
[PPT] _ Unit 3 _ Experiment.pptx[PPT] _ Unit 3 _ Experiment.pptx
[PPT] _ Unit 3 _ Experiment.pptx
 
CAT 2 _ List of Templates.pptx
CAT 2 _ List of Templates.pptxCAT 2 _ List of Templates.pptx
CAT 2 _ List of Templates.pptx
 
Design Thinking - Empathize Phase
Design Thinking - Empathize PhaseDesign Thinking - Empathize Phase
Design Thinking - Empathize Phase
 
CAT-II Answer Key.pdf
CAT-II Answer Key.pdfCAT-II Answer Key.pdf
CAT-II Answer Key.pdf
 
PSP LAB MANUAL.pdf
PSP LAB MANUAL.pdfPSP LAB MANUAL.pdf
PSP LAB MANUAL.pdf
 
18CSL51 - Network Lab Manual.pdf
18CSL51 - Network Lab Manual.pdf18CSL51 - Network Lab Manual.pdf
18CSL51 - Network Lab Manual.pdf
 
DS LAB MANUAL.pdf
DS LAB MANUAL.pdfDS LAB MANUAL.pdf
DS LAB MANUAL.pdf
 
CAT 1 _ List of Templates.pptx
CAT 1 _ List of Templates.pptxCAT 1 _ List of Templates.pptx
CAT 1 _ List of Templates.pptx
 
[PPT] _ UNIT 1 _ COMPLETE.pptx
[PPT] _ UNIT 1 _ COMPLETE.pptx[PPT] _ UNIT 1 _ COMPLETE.pptx
[PPT] _ UNIT 1 _ COMPLETE.pptx
 
CAT-1 Answer Key.doc
CAT-1 Answer Key.docCAT-1 Answer Key.doc
CAT-1 Answer Key.doc
 
Unit 3 Complete.pptx
Unit 3 Complete.pptxUnit 3 Complete.pptx
Unit 3 Complete.pptx
 
[PPT] _ Unit 2 _ 9.0 _ Domain Specific IoT _Home Automation.pdf
[PPT] _ Unit 2 _ 9.0 _ Domain Specific IoT _Home Automation.pdf[PPT] _ Unit 2 _ 9.0 _ Domain Specific IoT _Home Automation.pdf
[PPT] _ Unit 2 _ 9.0 _ Domain Specific IoT _Home Automation.pdf
 

Kürzlich hochgeladen

chapter 5.pptx: drainage and irrigation engineering
chapter 5.pptx: drainage and irrigation engineeringchapter 5.pptx: drainage and irrigation engineering
chapter 5.pptx: drainage and irrigation engineeringmulugeta48
 
AKTU Computer Networks notes --- Unit 3.pdf
AKTU Computer Networks notes ---  Unit 3.pdfAKTU Computer Networks notes ---  Unit 3.pdf
AKTU Computer Networks notes --- Unit 3.pdfankushspencer015
 
Online banking management system project.pdf
Online banking management system project.pdfOnline banking management system project.pdf
Online banking management system project.pdfKamal Acharya
 
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Christo Ananth
 
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance BookingCall Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance Bookingroncy bisnoi
 
Thermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - VThermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - VDineshKumar4165
 
Thermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.pptThermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.pptDineshKumar4165
 
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...ranjana rawat
 
Double Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torqueDouble Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torqueBhangaleSonal
 
Unleashing the Power of the SORA AI lastest leap
Unleashing the Power of the SORA AI lastest leapUnleashing the Power of the SORA AI lastest leap
Unleashing the Power of the SORA AI lastest leapRishantSharmaFr
 
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Bookingdharasingh5698
 
Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)simmis5
 
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756dollysharma2066
 
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...roncy bisnoi
 
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptxBSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptxfenichawla
 
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete RecordCCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete RecordAsst.prof M.Gokilavani
 
Call for Papers - International Journal of Intelligent Systems and Applicatio...
Call for Papers - International Journal of Intelligent Systems and Applicatio...Call for Papers - International Journal of Intelligent Systems and Applicatio...
Call for Papers - International Journal of Intelligent Systems and Applicatio...Christo Ananth
 
Double rodded leveling 1 pdf activity 01
Double rodded leveling 1 pdf activity 01Double rodded leveling 1 pdf activity 01
Double rodded leveling 1 pdf activity 01KreezheaRecto
 

Kürzlich hochgeladen (20)

chapter 5.pptx: drainage and irrigation engineering
chapter 5.pptx: drainage and irrigation engineeringchapter 5.pptx: drainage and irrigation engineering
chapter 5.pptx: drainage and irrigation engineering
 
AKTU Computer Networks notes --- Unit 3.pdf
AKTU Computer Networks notes ---  Unit 3.pdfAKTU Computer Networks notes ---  Unit 3.pdf
AKTU Computer Networks notes --- Unit 3.pdf
 
Online banking management system project.pdf
Online banking management system project.pdfOnline banking management system project.pdf
Online banking management system project.pdf
 
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
 
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort ServiceCall Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
 
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance BookingCall Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
 
Thermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - VThermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - V
 
Thermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.pptThermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.ppt
 
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
 
Double Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torqueDouble Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torque
 
Unleashing the Power of the SORA AI lastest leap
Unleashing the Power of the SORA AI lastest leapUnleashing the Power of the SORA AI lastest leap
Unleashing the Power of the SORA AI lastest leap
 
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
 
Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)
 
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
 
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
 
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar ≼🔝 Delhi door step de...
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar  ≼🔝 Delhi door step de...Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar  ≼🔝 Delhi door step de...
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar ≼🔝 Delhi door step de...
 
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptxBSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
 
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete RecordCCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
 
Call for Papers - International Journal of Intelligent Systems and Applicatio...
Call for Papers - International Journal of Intelligent Systems and Applicatio...Call for Papers - International Journal of Intelligent Systems and Applicatio...
Call for Papers - International Journal of Intelligent Systems and Applicatio...
 
Double rodded leveling 1 pdf activity 01
Double rodded leveling 1 pdf activity 01Double rodded leveling 1 pdf activity 01
Double rodded leveling 1 pdf activity 01
 

File Handling and Preprocessor Directives

  • 1. UNIT III : File Handling and Preprocessor Directives By Mr.S.Selvaraj Asst. Professor (SRG) / CSE Kongu Engineering College Perundurai, Erode, Tamilnadu, India Thanks to and Resource from : Sumitabha Das, “Computer Fundamentals and C Programming”, 1st Edition, McGraw Hill, 2018. 20CST21 – Programming and Linear Data Structures
  • 2. Syllabus – Unit Wise 6/9/2021 3.1 _ File Handling Basics 2
  • 3. List of Exercises 6/9/2021 3.1 _ File Handling Basics 3
  • 4. Text Book and Reference Book 6/9/2021 3.1 _ File Handling Basics 4
  • 5. Unit III : Contents 1. File Handling Basics 2. Text and Binary files 3. Opening and closing files 4. Detecting the End-Of-File, File pointer and file buffer 5. File read/write functions 6. Formatted functions fscanf() and fprintf() 7. Reading and writing binary files 8. Manipulating file position indicator 9. Renaming and Removing a file 10. Command line Arguments 11. Preprocessor 12. #define macros with and without arguments 13. #include directive 14. Conditional Compilation 6/9/2021 5 3.1 _ File Handling Basics
  • 6. File Handling Basics • So far, the input to the C programs is given from the prompt / terminal. • When a program is terminated, the entire input data is lost. • Storing in a file will preserve the data even if the program terminates. • Also to handle a large number of data, it will take a lot of time to feed them through the terminal. • If those data are stored in a file, then it is easy to access them from the file using the file handling functions in C. • In C programming, a file represents a sequence of bytes on the disk where a group of related data is stored. • All file handling functions are available in <stdio.h> header file. 6/9/2021 3.1 _ File Handling Basics 6
  • 7. Types of Files • There are two types of files exists in C Programming. • They are: – Text files – Binary files 6/9/2021 3.1 _ File Handling Basics 7
  • 8. Text Files • Text files contain ASCII codes of digits, alphabetic and symbols. • Text files are the normal files that can be easily created using Notepad or any simple text editors with an extension “.txt”. • When opening those files, it is possible to see all the contents as plain text. • We can easily edit or delete the contents. • Plus and Minus of Text Files: – They take minimum effort to maintain (+) – Easily readable (+) – provide least security (-) – takes bigger storage space (-) 6/9/2021 3.1 _ File Handling Basics 8
  • 9. Binary Files • Instead of storing data in plain text, they store it in the binary form (0's and 1's). • Binary files usually have an extension “.bin”. • Plus and Minus of Binary Files: – They can hold higher amount of data (-) – not readable easily (-) – provides a better security than text files (+) • For example, given the integer number 12345. – we could store it as individual characters 1, 2, 3, 4, and 5, using one byte for each character in text file as 6/9/2021 3.1 _ File Handling Basics 9
  • 10. • 1. Opening a New/Existing file • 2. Writing data into a file • 3. Reading data from the file • 4. Closing a file Operations on Files 6/9/2021 10 3.1 _ File Handling Basics
  • 11. Opening a New/Existing file • When working with files, it is mandatory to declare a pointer of type FILE as below: • The FILE is a structure data type defined in <stdio.h>. • This declaration is needed for communication between the file and program. • A file should be opened before any operation is being performed on it. 6/9/2021 3.1 _ File Handling Basics 11
  • 12. Opening a New/Existing file • The syntax of fopen() is given by, • In the above format, the arguments “path” and “mode” are strings. • The fopen() – returns a pointer to FILE structure on success – else it returns NULL. 6/9/2021 3.1 _ File Handling Basics 12
  • 13. Opening a New/Existing file • Every file on the disk has a name known as filename. • The filename can be specified as either absolute path or relative path. • In the absolute path, the complete location of the file is given whereas only partial path is mentioned in the relative path. 6/9/2021 3.1 _ File Handling Basics 13
  • 14. Opening a New/Existing file • The file mode specifies the kind of operation performed on the file. • The various file modes are given in the following table: 6/9/2021 3.1 _ File Handling Basics 14
  • 15. Opening a New/Existing file 6/9/2021 3.1 _ File Handling Basics 15
  • 16. Create a New File using fopen() • To create a new text file “file1.txt”, we can open the file in write mode(“w”) as given below: • In the above example, suppose the file “file1.txt” already exist in the location E:CPrograms. • The fopen() removes all the contents from the file “file1.txt” and creates a new empty file named “file1.txt”. • If “file1.txt”does not exist, new empty file named “file1.txt” is created. 6/9/2021 3.1 _ File Handling Basics 16
  • 17. Read file contents • To read the contents of the text file “sample.txt”, we can open the file in read mode(“r”) as given below: • In the above example, suppose the text file “sample.txt” exists in the current working directory. • The function fopen() opens the file for reading in text mode. • The reading mode only allows us to read the file, we cannot write into the file. 6/9/2021 3.1 _ File Handling Basics 17
  • 18. Difference between Append and Write Mode • Both write (w) mode and append (a) mode are used to write data into a file. • In both the modes, new file is created if it doesn't exist already. • The only difference is, when a file is opened in the write mode, the file is reset, resulting in deletion of any data already present in the file. • While in append mode this will not happen. • Append mode is used to append or add data to the existing data of file (if any). • Hence, when a file is opened in append (a) mode, the file pointer/cursor is positioned at the end of the file. 6/9/2021 3.1 _ File Handling Basics 18
  • 19. Example 1 6/9/2021 3.1 _ File Handling Basics 19
  • 20. Example 2: char filename[80]; FILE *fp; printf(“Enter the filename to be opened”); gets(filename); fp = fopen(filename,“w”); 6/9/2021 20 3.1 _ File Handling Basics Example 2
  • 21. • The file should be closed after performing read/write operation. • Closing of a file is performed using the function fclose(). • Closing a file frees the file pointer (file pointer is disconnected from a file) and associated buffers. • The fclose() will close the file specified by the fptr whereas the fcloseall() closes all the files that are already opened. • The fclose() function – returns 0 if close operation is successful or – returns EOF if an error was encountered. Closing a File 6/9/2021 21 3.1 _ File Handling Basics
  • 22. Detecting the End-of-File (EOF) • While performing read and write operations on files, we do not know exactly how long the file is. • Usually, we read data from the beginning to the end of the file. • To identify the reach of end-of-file (EOF), there are two ways available. 6/9/2021 3.1 _ File Handling Basics 22
  • 23. Way 1 • While reading the file in text mode by character at a time, we can compare the character that has been read with EOF, which is a symbolic constant defined in stdio.h whose value is set to -1. • The following code snippet does that, 6/9/2021 3.1 _ File Handling Basics 23
  • 24. Way 2 • The other way is the use of feof( ) function defined in stdio.h. • The syntax of feof( ) is given by: • The function returns 0 (false) when the end of the file has not been reached and a non-zero value (true) if the EOF has been reached. • A simple code snippet using feof( ) is given as 6/9/2021 3.1 _ File Handling Basics 24
  • 25. • fopen has two important consequences – creation of a file pointer and file buffer • File pointer is a variable that points to a structure typedef to FILE. • FILE contains the following information related to the opened file – The mode of opening. – The location of the file buffer. – The file position indicator. – Whether EOF or any errors have been encountered on reading or writing. • File position indicator also called file offset pointer, plays important role in input/output operations Detecting the file pointer and file buffer 6/9/2021 25 3.1 _ File Handling Basics
  • 26. • When a file is read with fgetc, data is first sent from disk to the buffer. Detecting the file pointer and file buffer 6/9/2021 26 3.1 _ File Handling Basics
  • 27. Example 3: FILE *fp; fp = fopen(“data.dat”,“r”); if(fp == NULL) { printf(“Can not open data.datn”); exit(1); } Or FILE *fp; if((fp = fopen(“data.dat”, “r”)) ==NULL) { printf(“Can not open data.datn”); exit(1); } 6/9/2021 27 3.1 _ File Handling Basics Detecting File Pointer
  • 28. Thank you 6/9/2021 3.1 _ File Handling Basics 28
  • 29. UNIT III : File Handling and Preprocessor Directives By Mr.S.Selvaraj Asst. Professor (SRG) / CSE Kongu Engineering College Perundurai, Erode, Tamilnadu, India Thanks to and Resource from : Sumitabha Das, “Computer Fundamentals and C Programming”, 1st Edition, McGraw Hill, 2018. 20CST21 – Programming and Linear Data Structures
  • 30. Unit III : Contents 1. File Handling Basics 2. Text and Binary files 3. Opening and closing files 4. Detecting the End-Of-File, File pointer and file buffer 5. File read/write functions 6. Formatted functions fscanf() and fprintf() 7. Reading and writing binary files 8. Manipulating file position indicator 9. Renaming and Removing a file 10. Command line Arguments 11. Preprocessor 12. #define macros with and without arguments 13. #include directive 14. Conditional Compilation 6/9/2021 30 3.2 _ Reading and Writing Functions in Files
  • 31. Input and Output Operations • A C program can read data from the keyboard and writes data into the monitor. • Similarly, it can read and write from/into the file as shown in the diagram. 6/9/2021 3.2 _ Reading and Writing Functions in Files 31
  • 32. Input and Output Operations • A number of functions are available for performing operations on files. • They are classified as formatted File I/O and unformatted File I/O functions. • The formatted functions deal with all kind of data whereas the unformatted functions deal only character data type. • Different functions are also available for handling text as well as binary files. 6/9/2021 3.2 _ Reading and Writing Functions in Files 32
  • 33. List of read/input functions • To perform read operations the following functions are used. – fgetc ( ) – fgets ( ) – fscanf ( ) – fread ( ) 6/9/2021 3.2 _ Reading and Writing Functions in Files 33
  • 34. List of write/output functions • To perform read operations the following functions are used. – fputc ( ) – fputs ( ) – fprintf ( ) – fwrite ( ) 6/9/2021 3.2 _ Reading and Writing Functions in Files 34
  • 35. • Character-oriented functions (fgetc and fputc) • Line-oriented functions (fgets and fputs) • Formatted functions (fscanf and fprintf) • Array- and structure-oriented functions (fread and fwrite) • All the functions use the file pointer as argument and work with any file including stdin, stdout and stderr. List of Read/Write functions 6/9/2021 35 3.2 _ Reading and Writing Functions in Files
  • 36. Reading and Writing to a text file using fgetc () and fputc () • fgetc () reads the content of the file character by character. • After reading a character from the file, fgetc() function moves the file pointer to next character in the file. • The fgetc () function returns the next character from the file specified. • It returns EOF if end-of-file is reached or error occurred. 6/9/2021 3.2 _ Reading and Writing Functions in Files 36
  • 37. Example 1 • Assume there is a text file “file1.txt” with the content “Hello World!” . Write the C program to read that file one character at a time using fgetc() function and display it on the monitor. 6/9/2021 3.2 _ Reading and Writing Functions in Files 37
  • 38. 6/9/2021 3.2 _ Reading and Writing Functions in Files 38
  • 39. fputc ( ) function • The function fputc ( ) writes a character to the specified file and automatically advances the file pointer to the next position in the file. – On success, the written character is returned by the function. – If pointer is at end of file or if an error occurs EOF file is returned by this function. • Syntax: – char − This is the character to be written. – fptr − This is the pointer to a specified file that indicates where the character is to be written. 6/9/2021 3.2 _ Reading and Writing Functions in Files 39
  • 40. Example 2 • Write a c program to write the string “Engineers create the World” in the file sample.txt using fputc() function. 6/9/2021 3.2 _ Reading and Writing Functions in Files 40
  • 41. 6/9/2021 3.2 _ Reading and Writing Functions in Files 41
  • 42. Reading and Writing to a text file using fgets () and fputs () • The function fgets() is used to read a file line by line. – str − This is the pointer to an array of characters where the string read is stored. – size − This is the maximum number of characters to be read (including terminating character “0”). Usually, the length of the array “str” is used. – fptr − This is the pointer that identifies the file where characters are read from. 6/9/2021 3.2 _ Reading and Writing Functions in Files 42
  • 43. Reading and Writing to a text file using fgets () and fputs () • fgets ( ) reads a line from the specified file and stores it into the string pointed to by str. – It stops when (size-1) characters are read or – the newline character is read, or – the end-of-file is reached, whichever comes first. • While all the characters are read without any error, a null (“ 0” ) character is appended to the end of the string. • On success, fgets () returns the same str parameter. • If end-of-file is encountered or an error occurred, a NULL value is returned. 6/9/2021 3.2 _ Reading and Writing Functions in Files 43
  • 44. Example 3 • Again consider the text file “file1.txt”. Now, write a C program to read the file using fgets() function and read 4 characters at a time and those are displayed in the monitor. 6/9/2021 3.2 _ Reading and Writing Functions in Files 44
  • 45. 6/9/2021 3.2 _ Reading and Writing Functions in Files 45
  • 46. fputs ( ) function • This function is used to write a string into the file. • It has two arguments, – pointer to string and – file pointer. • It writes a null-terminated string to the file. • The null character is not written to the file. • On success, fputs( ) returns Non-negative value. • On error, it returns EOF or Negative value. • str − This is an array containing a string (terminated by “0”) to be written into a file. • fptr − This is the pointer to a specified file that identifies the stream where the string is to be written. 6/9/2021 3.2 _ Reading and Writing Functions in Files 46
  • 47. Example 4 • Write a C program to write 5 strings into the file sample.txt using fputs() function. 6/9/2021 3.2 _ Reading and Writing Functions in Files 47
  • 48. 6/9/2021 3.2 _ Reading and Writing Functions in Files 48
  • 49. Reading and Writing to a text file using fscanf() and fprintf () • For reading and writing to a text file, we use the functions fscanf() and fprintf() . • They are just the file versions of scanf() and printf(). • The only difference is that fscanf() and fprint() expects a pointer to the structure FILE. • Other functions like fgetchar(), fputc() etc. can be used in a similar way. 6/9/2021 3.2 _ Reading and Writing Functions in Files 49
  • 50. fscanf ( ) function • The functions fgetc ( ) and fgets ( ) are used for reading only character data. • But, fscanf ( ) can read different types of data such as int, float, char, etc., from the given file. • On success, this function returns the number of input items successfully matched and assigned to argument specified. • On failure, it returns EOF. 6/9/2021 3.2 _ Reading and Writing Functions in Files 50
  • 51. fscanf ( ) function • The parameters used in the fscanf() are: – fptr − This is the pointer that identifies the file where characters are read from. – format-string – This is a string which controls the interpretation of the argument list. A format specification causes the fscanf() function to read and convert characters in the input into values of a specified type. – argument-list - The value read from the file based on format-string is assigned to an argument in the argument list. 6/9/2021 3.2 _ Reading and Writing Functions in Files 51
  • 52. Example 5 • Write a C program to Read the integer number from a file sample.txt using fscanf() function. 6/9/2021 3.2 _ Reading and Writing Functions in Files 52
  • 53. 6/9/2021 3.2 _ Reading and Writing Functions in Files 53
  • 54. fprintf () function • Like fscanf( ), the function fprintf( ) handles different types of data. • It can be used for writing formatted data into the file. • On success, fprintf( ) returns the total number of bytes written to the file. • On error, it returns EOF. 6/9/2021 3.2 _ Reading and Writing Functions in Files 54
  • 55. Example 6 • Write a C program to Read the details about n students from the user and write those information into the file sample.txt using fprintf() function. 6/9/2021 3.2 _ Reading and Writing Functions in Files 55
  • 56. 6/9/2021 3.2 _ Reading and Writing Functions in Files 56
  • 57. Reading and Writing to a text file using fread() and fwrite () • The functions fgetc(), fgets() and fscanf() are used to read data from text files. • The function fread() is used to get data from binary files. • In binary files, information is stored in the form of binary and it can be read directly into memory with no need of any processing to interpret it. • Hence, handling of files in binary mode is significantly faster than text mode. • On success, fread() returns the number of items read from the file. • On error or EOF, it returns a number less than “n”. 6/9/2021 3.2 _ Reading and Writing Functions in Files 57
  • 58. fread() function • Syntax: – ptr – It is the starting address of the memory block where data is to be read. – size – Item size in bytes. – n- It indicates the maximum number of items read from the file – fptr –It specifies the pointer to file from where the data has to be read. • The following code snippet discuss about the different ways in which fread() can be used. 6/9/2021 3.2 _ Reading and Writing Functions in Files 58
  • 59. 6/9/2021 3.2 _ Reading and Writing Functions in Files 59
  • 60. fwrite() function • fwrite( ) function is used to write binary data into the file. • It accepts the same arguments as fread( ). • Syntax: • On success, it returns the number of items successfully written to the file. • On error, it returns a number less than n. • The following code snippets show the usage of fwrite() function in handling different data. 6/9/2021 3.2 _ Reading and Writing Functions in Files 60
  • 61. 6/9/2021 3.2 _ Reading and Writing Functions in Files 61 The first fwrite( ) function writes only the first three elements of the array into the file. But, the second one writes the last three elements of the array into the file.
  • 62. Example 7 • Write a C Program to Write the details about 3 students into the file sample.txt using fwrite() function. 6/9/2021 3.2 _ Reading and Writing Functions in Files 62
  • 63. 6/9/2021 3.2 _ Reading and Writing Functions in Files 63
  • 64. 6/9/2021 3.2 _ Reading and Writing Functions in Files 64
  • 65. Practice Problem 1 • Get a line of text from the user and write it into a file named „sample.txt‟. Read the contents from the file and display it on the monitor. Use fgetc() and fputc() functions to manipulate the file. 6/9/2021 3.2 _ Reading and Writing Functions in Files 65
  • 66. Practice Problem 2 • Write a program to copy the content of one file into another one. Get the source and target file names from the user. 6/9/2021 3.2 _ Reading and Writing Functions in Files 66
  • 67. Practice Problem 3 • Write a C program to compare two files for checking whether two files contains the same content or not. 6/9/2021 3.2 _ Reading and Writing Functions in Files 67
  • 68. Practice Problem 5 • Write a program to add some content at the end to the existing file. 6/9/2021 3.2 _ Reading and Writing Functions in Files 68
  • 69. Practice Problem 5 • Write a program to get the details (such as Name, Roll No, five subjects marks ) of N students and find the Total mark and Rank for each student. Write Name, RollNo, Total mark and Rank for each student into a file named “studentdb.txt” using formatted file I/O functions and also display these details in tabular format. 6/9/2021 3.2 _ Reading and Writing Functions in Files 69
  • 70. Practice Problem 6 • Write a program to create and manage a student database with the listed operations 1. Add a new student by giving his/her roll number, name and average mark. 2. Display the details about a student for a given roll number 3. Display the details of all students in the database 4. Update the average mark of a student for a given roll number 5. Delete a student record if roll number is given 6/9/2021 3.2 _ Reading and Writing Functions in Files 70
  • 71. Thank you 6/9/2021 3.2 _ Reading and Writing Functions in Files 71
  • 72. UNIT III : File Handling and Preprocessor Directives By Mr.S.Selvaraj Asst. Professor (SRG) / CSE Kongu Engineering College Perundurai, Erode, Tamilnadu, India Thanks to and Resource from : Sumitabha Das, “Computer Fundamentals and C Programming”, 1st Edition, McGraw Hill, 2018. 20CST21 – Programming and Linear Data Structures
  • 73. Unit III : Contents 1. File Handling Basics 2. Text and Binary files 3. Opening and closing files 4. Detecting the End-Of-File, File pointer and file buffer 5. File read/write functions 6. Formatted functions fscanf() and fprintf() 7. Reading and writing binary files 8. Manipulating file position indicator 9. Renaming and Removing a file 10. Command line Arguments 11. Preprocessor 12. #define macros with and without arguments 13. #include directive 14. Conditional Compilation 6/9/2021 73 3.3 _ Manipulating, Removing and Renaming a File
  • 74. Sequential Access and Random Access Files • Based on the method of accessing the data stored, files can be classified into two types. – Sequential access file – Random access file • In the sequential access file, data is kept in sequential order. To access the last record of the file, we need to read all records preceding to that record. – Hence, it takes more time. • But, in random access files data can be read and modified at any random position. Unlike sequential access, the any record can be read directly. – Hence, it takes less time. 6/9/2021 3.3 _ Manipulating, Removing and Renaming a File 74
  • 75. Difference b/w Sequential and Random Access Files 6/9/2021 3.3 _ Manipulating, Removing and Renaming a File 75
  • 76. Random Accessing in Files • To achieve random accessing in files, the following functions are used – fseek() – ftell() – rewind() 6/9/2021 3.3 _ Manipulating, Removing and Renaming a File 76
  • 77. Manipulating file position indicator using fseek( ) function • If there are many records inside a file and need to access a record at a specific position fseek( ) is used. • As the name suggests, fseek() moves file pointer associated with a given file to a specific position. • The fseek() function returns 0 if the move is successful, else it returns a non-zero value. 6/9/2021 3.3 _ Manipulating, Removing and Renaming a File 77
  • 78. fseek() function • fptr - It is the pointer to the file. • Offset - It indicates the number of bytes to move from the position specified by the third argument. The positive value of offset makes the move in the forward direction whereas the negative value in the backward(reverse) direction. • Position - It defines the point with respect to which the file pointer needs to be moved. It has three values: 6/9/2021 3.3 _ Manipulating, Removing and Renaming a File 78
  • 79. Example 6/9/2021 3.3 _ Manipulating, Removing and Renaming a File 79
  • 80. ftell( ) function • The ftell() function is used to return the position of file pointer in the file with respect to starting of the file. 6/9/2021 3.3 _ Manipulating, Removing and Renaming a File 80
  • 81. Example • The value of p is 12 which also indicate the size of the file. 6/9/2021 3.3 _ Manipulating, Removing and Renaming a File 81
  • 82. rewind( ) function • The rewind function sets the file position to the beginning of the file. • The rewind( ) is equivalent to – fseek (fptr, 0, SEEK_SET). 6/9/2021 3.3 _ Manipulating, Removing and Renaming a File 82
  • 83. Example • Write a program to reverse the contents of the text file using fseek() function. 6/9/2021 3.3 _ Manipulating, Removing and Renaming a File 83
  • 84. 6/9/2021 3.3 _ Manipulating, Removing and Renaming a File 84
  • 85. Removing a file : remove ( ) function • The remove function can be used to delete a file that is not opened already. • The function returns zero if file is deleted successfully, else returns a non-zero value. 6/9/2021 3.3 _ Manipulating, Removing and Renaming a File 85
  • 86. Renaming a file: rename ( ) function • The function rename() is used to change the name of the file • i.e. from old_name to new_name without changing the content present in the file. • Syntax: – If the file is renamed successfully, zero is returned. – On failure, a nonzero value is returned. 6/9/2021 3.3 _ Manipulating, Removing and Renaming a File 86
  • 87. Thank you 6/9/2021 3.3 _ Manipulating, Removing and Renaming a File 87
  • 88. UNIT III : File Handling and Preprocessor Directives By Mr.S.Selvaraj Asst. Professor (SRG) / CSE Kongu Engineering College Perundurai, Erode, Tamilnadu, India Thanks to and Resource from : Sumitabha Das, “Computer Fundamentals and C Programming”, 1st Edition, McGraw Hill, 2018. 20CST21 – Programming and Linear Data Structures
  • 89. Unit III : Contents 1. File Handling Basics 2. Text and Binary files 3. Opening and closing files 4. Detecting the End-Of-File, File pointer and file buffer 5. File read/write functions 6. Formatted functions fscanf() and fprintf() 7. Reading and writing binary files 8. Manipulating file position indicator 9. Renaming and Removing a file 10. Command line Arguments 11. Preprocessor 12. #define macros with and without arguments 13. #include directive 14. Conditional Compilation 6/9/2021 89 3.4 _ Command Line Arguments
  • 90. Command-line Arguments • Command line argument is a parameter supplied to the program when it is invoked. • It is possible to pass values from the command line to the C programs when they are executed. • These values are called command line arguments. • Executable code of the program should be compiled from DOS prompt. 6/9/2021 3.4 _ Command Line Arguments 90
  • 91. Command-line Arguments • The command line arguments are handled by arguments given in main() function. • The main() can be defined as, 6/9/2021 3.4 _ Command Line Arguments 91
  • 92. Command-line Arguments • The first argument argc refers to the number of arguments passed to main(). • and the second argument argv[] is an array of character pointers which points to each argument passed to the main(). 6/9/2021 3.4 _ Command Line Arguments 92
  • 93. Command-line Arguments • The array argv contains the elements – argv[0] holds the name of the program itself. – argv[1] is a pointer to the first command line argument supplied – argv[2] is a pointer to the second command line argument supplied – ……. – argv[argc-1] is a pointer to the last command line argument supplied to the program. • If no argument is supplied to the program, the parameter argc will be set to one. • if one argument is passed then argc is set to 2. 6/9/2021 3.4 _ Command Line Arguments 93
  • 94. Command-line Arguments • Steps to be followed to execute program using Command Line Argument inside Borland C Compiler : – Step 1 : Enter a Program and compile it. – Step 2 : Open File menu inside Borland C. – Step 3 : Click on DOS Shell. – Step 4 : In the Command Prompt type the filename (Program name without any extension) with the arguments and press Enter Key using the format “filename value 1 value 2 ..... Value m” . Program will be executed with the given arguments and output is generated. – Step 5 : Type “exit” command to return to Borland C 6/9/2021 3.4 _ Command Line Arguments 94
  • 95. Example 1 • Write an example program to checks if there is any argument supplied from the command line and display these arguments. 6/9/2021 3.4 _ Command Line Arguments 95
  • 96. 6/9/2021 3.4 _ Command Line Arguments 96
  • 97. Example 2 • Write a program to add all the numbers given as Command Line Arguments. 6/9/2021 3.4 _ Command Line Arguments 97
  • 98. 6/9/2021 3.4 _ Command Line Arguments 98
  • 99. Example 3 • Write a program to copy one file into another file using command line argument. 6/9/2021 3.4 _ Command Line Arguments 99
  • 100. 6/9/2021 3.4 _ Command Line Arguments 100
  • 101. 6/9/2021 3.4 _ Command Line Arguments 101
  • 102. 6/9/2021 3.4 _ Command Line Arguments 102
  • 103. Problem 1 6/9/2021 3.4 _ Command Line Arguments 103
  • 104. Thank you 6/9/2021 3.4 _ Command Line Arguments 104
  • 105. UNIT III : File Handling and Preprocessor Directives By Mr.S.Selvaraj Asst. Professor (SRG) / CSE Kongu Engineering College Perundurai, Erode, Tamilnadu, India Thanks to and Resource from : Sumitabha Das, “Computer Fundamentals and C Programming”, 1st Edition, McGraw Hill, 2018. 20CST21 – Programming and Linear Data Structures
  • 106. Unit III : Contents 1. File Handling Basics 2. Text and Binary files 3. Opening and closing files 4. Detecting the End-Of-File, File pointer and file buffer 5. File read/write functions 6. Formatted functions fscanf() and fprintf() 7. Reading and writing binary files 8. Manipulating file position indicator 9. Renaming and Removing a file 10. Command line Arguments 11. Preprocessor 12. #define macros with and without arguments 13. #include directive 14. Conditional Compilation 6/9/2021 106 3.5 _ Preprocessor
  • 107. Preprocessor • As the name suggests preprocessors are programs that processes the source code before compilation as shown in figure. • Preprocessor provides preprocessor directives which tell the compiler to preprocess the source code before the complier starts its work. • All the preprocessor directives begin with a “#” (hash) symbol. • The preprocessor directives can be placed anywhere in the program. 6/9/2021 3.5 _ Preprocessor 107
  • 108. Types of Preprocessor directives • There are three different types of preprocessor directives : – Macros – File Inclusion – Conditional Compilation 6/9/2021 3.5 _ Preprocessor 108
  • 109. Macros • Macros are piece of code in a program which is assigned with some name. • Whenever this name is encountered by the compiler the compiler replaces the name with the actual piece of code. • The “#define” directive is used to define a macro. • There are two types of macros – – one which takes the argument and – another which does not take any argument. 6/9/2021 3.5 _ Preprocessor 109
  • 110. Difference between Macros and Functions 6/9/2021 3.5 _ Preprocessor 110
  • 111. Macros without argument • Every occurrences of macro name is replaced with the actual piece of code by the compiler. • This kind of macros usually used to give symbolic names to numeric constants. • There is no semi-colon(“;‟) is needed at the end of a macro definition. 6/9/2021 3.5 _ Preprocessor 111
  • 112. Example 6/9/2021 3.5 _ Preprocessor 112
  • 113. Macros with arguments • It is also possible to pass arguments to macros. • Macro with arguments works similarly as functions. 6/9/2021 3.5 _ Preprocessor 113
  • 114. Example 6/9/2021 3.5 _ Preprocessor 114
  • 115. Nesting of macros • macro may be used in the definition of another macro. This is known as nesting of macros. 6/9/2021 3.5 _ Preprocessor 115
  • 116. Example 6/9/2021 3.5 _ Preprocessor 116
  • 117. File Inclusion • The #include preprocessor is used to include header files to a C program. • This directive instructs the compiler to include a specified file to the C program. • Here, "stdio.h" is a header file. • The #include preprocessor directive replaces the above line with the contents of stdio.h header file which contain function and macro definitions. 6/9/2021 3.5 _ Preprocessor 117
  • 118. File Inclusion • Rules for file inclusion are: – 1. File inclusive Directives are used to include standard or user define header file inside C Program. – 2. File inclusive directory checks included header file inside same directory (if path is not mentioned). – 3. File inclusive directives begins with #include – 4. If Path is mentioned then it will include the header file present in the location specified by that path. – 5. Instead of using triangular brackets we use “Double Quote” for inclusion of user defined header file. 6/9/2021 3.5 _ Preprocessor 118
  • 119. Including Standard Header Files 6/9/2021 3.5 _ Preprocessor 119
  • 120. Including User Defined Header Files 6/9/2021 3.5 _ Preprocessor 120
  • 121. Conditional Compilation • Conditional compilation is the process of selecting which code to compile and which code to not compile similar to the #if / #else / #endif in C and C++. • Conditional Compilation directives helps to include or skip a specific block of code in the source code based on some conditions. • This can be done with the help of “ifdef” and “endif” preprocessing directives. • If the macro in #ifdef is defined, then the block of statements will be executed normally. But, if it is not defined, then the compiler will simply skip that block of statements. 6/9/2021 3.5 _ Preprocessor 121
  • 123. Example 6/9/2021 3.5 _ Preprocessor 123
  • 124. Thank you 6/9/2021 3.5 _ Preprocessor 124