Unit 5
Unit 5
Files: Types of files, Modes of Operations, File input and output, File Handling Functions, Random
Access Functions, Command Line Arguments, Preprocessor Directives
FILES: A file represents a sequence of bytes on the disk. A File can be used to store a large volume of
data.
A file is a container in computer storage devices used for storing data.
Why files are needed?
When a program is terminated, the entire data is lost. Storing in a file will preserve your data
even if the program terminates.
If you have to enter a large number of data, it will take a lot of time to enter them all.
However, if you have a file containing all the data, you can easily access the contents of the file
using a few commands in C.
You can easily move your data from one computer to another without any changes.
Types of Files:
A C program uses four types of files as follows:
2. At times the programmer may want to change or add the subroutines and reflect those changes in all
the programs. For doing this, he will have to only change the source file for the subroutines, recompile
the source code and then recompile and re-link the program.
This tells us that including a header file will make it easier at all levels of the program. If we need to
modify anything then changes are made only in the subroutines after which all the changes will be
reflected.
C provides us with some standard header files which are available easily.
The header files are added at the start of the source code so that they can be used by more than one
function of the same file.
3. Object files
They are the files that are generated by the compiler as the source code file is processed.
These files generally contain the binary code of the function definitions.
The object file is used by the linker for producing an executable file for combining the object files
together. It has a '.o' extension.
4. Executable file
This file is generated by the linker.
Page 3 of 30
Programming for Problem Solving Using ‘C’ Unit-V
Various object files are linked by the linker for producing a binary file which will be executed directly.
They have an '.exe' extension.
When dealing with files, there are two types of files.
1. Text files
2. Binary files
1. Text files
Text files are the normal .txt files. You can easily create text files using any simple text editors such as
Notepad. When you open those files, you'll see all the contents within the file as plain text. You can
easily edit or delete the contents. They take minimum effort to maintain, are easily readable, and
provide the least security and takes bigger storage space.
2. Binary files
Binary files are mostly the .bin files in your computer. Instead of storing data in plain text, they store
data in the binary form (0's and 1's). They can hold a higher amount of data, are not readable easily,
and provides better security than text files.
Modes of Operations
In programming, we may require some specific input data to be generated several numbers of times.
Sometimes, it is not enough to only display the data on the console. The data to be displayed may be
very large, and only a limited amount of data can be displayed on the console, and since the memory is
volatile, it is impossible to recover the programmatically generated data again and again. However, if
we need to do so, we may store it onto the local file system which is volatile and can be accessed every
time. Here, comes the need of file handling in C.
File handling in C enables us to create, update, read, and delete the files stored on the local file system
through our C program. The following operations can be performed on a file.
1. Creation of the new file
2. Opening an existing file
3. Reading from the file
4. Writing to the file
5. Deleting the file
Page 4 of 30
Programming for Problem Solving Using ‘C’ Unit-V
Function description
mode description
Page 5 of 30
Programming for Problem Solving Using ‘C’ Unit-V
Closing a File
The fclose() function is used to close an already opened file.
General Syntax :
int fclose( FILE *fp);
Here fclose() function closes the file and returns zero on success, or EOF if there is an error in closing
the file. This EOF is a constant defined in the header file stdio.h.
Page 6 of 30
Programming for Problem Solving Using ‘C’ Unit-V
fp = fopen("one.txt", "w");
printf("Enter data...");
while( (ch = getchar()) != EOF) {
putc(ch, fp);
}
fclose(fp);
fp = fopen("one.txt", "r");
do
{
fscanf(q,"%s %d", e.name, e.age);
printf("%s %d", e.name, e.age);
}
while(!feof(q));
}
In this program, we have created two FILE pointers and both are refering to the same file but in
different modes.
fprintf() function directly writes into the file, while fscanf() reads from the file, which can then be
printed on the console using standard printf() function.
Page 8 of 30
Programming for Problem Solving Using ‘C’ Unit-V
Example 1: fopen("E:\\cprogram\\newprogram.txt","w");
In the above example the file newprogram.txt doesn’t exists it will create and opens in mode
‘w’ for writing.
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.
Page 9 of 30
Programming for Problem Solving Using ‘C’ Unit-V
Mode “r”: It is a read only mode, which means if the file is opened in r mode, it won’t allow you to
write and modify content of it.
Mode “w”: It is a write only mode. The fopen() function creates a new file when the specified file
doesn’t exist and if it fails to open file then it returns NULL.
Mode “a”: Using this mode Content can be appended at the end of an existing file.
Mode “r+”: You are allowed to read, write and modify the content of file opened in “r+” mode.
Mode “w+”: Same as mode “w” apart from operations, which can be performed; the file can be read,
write and modified in this mode.
Mode “a+”: Same as mode “a”; you can read and append the data in the file, however content
modification is not allowed in this mode.
File Close(fclose): We should always close a file whenever the operations on file are over. It means
the contents and links to the file are terminated.
C' provides the fclose() function to perform file closing operation. The fclose function takes a file
pointer as an argument. It returns 0 if close was successful and EOF (end of file) if there is an error has
occurred while file closing.
Syntax: fclose (file_pointer); Example: FILE *fp;
fp = fopen ("data.txt", "r"); fclose (fp);
Page 10 of 30
Programming for Problem Solving Using ‘C’ Unit-V
scanf ("%f",&percentage);
printf(“\n Age: %d \n Percentage: %f “,age, percentage);
getch();
}
Output:
Enter your Age: 25
Enter your percentage: 100
Age: 25
Percentage: 100
3. fscanf(): The fscanf() function is used to read set of characters from file. It reads a word from
the file and returns EOF at the end of file.
Syntax: fscanf(file_pointer, conversion_specifiers, variable_adresses);
4. fprinf():The fprintf() function is used to write set of characters into file. It sends formatted
output to a stream.
Syntax: fprintf(file_pointer, str, variable_lists);
Eg: fprintf (fp, “%s %d”, “var1”, var2); Example:
#include <stdio.h>
#include <stdio.h>
#include <stdlib.h>
Page 11 of 30
Programming for Problem Solving Using ‘C’ Unit-V
void main()
{
FILE *fp;
char str[80], str1[80];
fp = fopen("data.txt","w");
printf("Enter string to be written in a file: ");
fscanf(stdin, "%s", str); /*Read from keyboard */
fprintf(fp, "%s", str); /*Write str to file */
fclose(fp);
fp = fopen("data.txt","r");
fscanf(fp, "%s", str1); /* read a word from file and copy into str1 */
fprintf(stdout, "%s", str1); /* print str1 on screen */
getch();
}
Output:
5. fgets():The fgets() function reads a line of characters from file. It gets string from a stream.
6. fputs():The fputs() function writes a line of characters into file. It outputs string to a stream.
Example:
include<stdio.h>
void main()
Page 12 of 30
Programming for Problem Solving Using ‘C’ Unit-V
{
FILE *fp;
char file[12],text[50]; int i=0;
fp = fopen(“line.txt” ,”w”);
printf(“Enter text here : “);
scanf(“%s”, text);
fputs(text, fp );
fclose(fp);
fp = fopen(“line.txt”, “r”);
if(fgets(text,50,fp )!=NULL)
while(text[i]!='\0')
{
putchar(text[i]); i++;
}
fclose(fp ); getch();
}
Output:
fgetc():The fgetc() function returns a single character from the file. It gets a character from the stream.
It returns EOF at the end of file.
Syntax: fgetc(file_pointer); Eg: c=fgetc(fp); Example:
#include <stdio.h>
int main ()
Page 13 of 30
Programming for Problem Solving Using ‘C’ Unit-V
{
FILE *fp = fopen("test.txt","r");
do
{
char c = fgetc(fp);
if (feof(fp))
break ;
printf("%c", c);
}
while(1);
fclose(fp);
return 0;
}
Output:
printf("%s", received_string);
fclose(fp);
return 0;
}
Output:
putchar():It transmits a single character to the standard output device (the computer screen). In case
you want to display more than one characters, use putchar() method in a loop.
Syntax: putchar(character variable);
getchar():This is a single character input function. getchar() reads a single character from the
standard input data stream, which is normally the keyboard. Since This function reads only single
character at a time. You can use this method in the loop in case you want to read more than one
character from the screen.
Syntax: character variable = getchar( );
Example:
#include <stdio.h>
void main( )
{
int c;
printf( "Enter a string :"); c = getchar( );
printf( "\nYou entered: "); putchar( c );
getch();
}
Output:
Enter a string Hello World
The string you entered is H
Page 15 of 30
Programming for Problem Solving Using ‘C’ Unit-V
In C language, the data stored in the file can be accessed in two ways:
1. Sequential Access
2. Random Access
If we want to read access record in the middle of the file and if the file size is too large sequential
access is not preferable. In this case, random access to file can be used, which allows to access any
record directly at any position in the file.
1. fseek()
This function is used for setting the file pointer at the specified byte.
Syntax
int fseek(FILE *fp, long displacement, int origin);
Here,
fp – file pointer
displacement – It denotes the number of bytes which are skipped nackward or forward from the
position specified in the third argument. It is a long integer which can be positive or negative
origin – It is the position relative to which the displacement takes place. It takes one of the
following three values.
Position
Constant Value
Page 16 of 30
Programming for Problem Solving Using ‘C’ Unit-V
SEEK_SET
0 Beginning of file
SEEK_CURRENT
1 Current position
SEEK_END
2 End of file
2. ftell()
This function returns the current position of the file position pointer. The value is counted from
the beginning of the file.
Syntax
long ftell(FILE *fp);
Page 17 of 30
Programming for Problem Solving Using ‘C’ Unit-V
3. rewind()
This function is used to move the file pointer to the beginning of the file. This function is useful
when we open file for update.
Syntax:
rewind(FILE *fp);
Here, fp is file pointer of type FILE
Consider below program to understand rewind() function
#include<stdio.h>
void main()
{
FILE *fp;
fp=fopen(“student.dat”,”rb+”);
if(fp==NULL)
{
printf(“Error in opening file\n”);
}
printf(“Position pointer %ld\n”,ftell(fp));
fseek(fp,0,2);
printf(“Position pointer %ld\n”,ftell(fp));
Page 18 of 30
Programming for Problem Solving Using ‘C’ Unit-V
rewind(fp);
printf(“Position pointer %ld\n”,ftell(fp));
fclose(fp);
}
It is possible to pass some values from the command line to your C programs when they are executed.
These values are called command line arguments and many times they are important for your
program especially when you want to control your program from outside instead of hard coding those
values inside the code.
The command line arguments are handled using main() function arguments where argc refers to the
number of arguments passed, and argv[] is a pointer array which points to each argument passed to the
program. Following is a simple example which checks if there is any argument supplied from the
command line and take action accordingly −
#include <stdio.h>
int main( int argc, char *argv[] )
{
if( argc == 2 )
{
printf("The argument supplied is %s\n", argv[1]);
}
else if( argc > 2 )
{
printf("Too many arguments supplied.\n");
}
else
{
printf("One argument expected.\n");
}
}
When the above code is compiled and executed with single argument, it produces the following result.
$./a.out testing
Page 19 of 30
Programming for Problem Solving Using ‘C’ Unit-V
Note : You pass all the command line arguments separated by a space, but if argument itself has a
space then you can pass such arguments by putting them inside double quotes “” or single quotes ”.
// C program to illustrate
// command line arguments
#include<stdio.h>
int main(int argc,char* argv[])
{
int counter;
printf("Program Name Is: %s",argv[0]);
if(argc==1)
printf("\nNo Extra Command Line Argument Passed Other Than Program Name");
if(argc>=2)
{
printf("\nNumber Of Arguments Passed: %d",argc);
printf("\n----Following Are The Command Line Arguments Passed----");
for(counter=0;counter<argc;counter++)
printf("\nargv[%d]: %s",counter,argv[counter]);
}
return 0;
}
1. Without argument: When the above code is compiled and executed without passing any
argument, it produces following output.
$ ./a.out
Program Name Is: ./a.out
No Extra Command Line Argument Passed Other Than Program Name
2. Three arguments : When the above code is compiled and executed with a three arguments, it
produces the following output.
$ ./a.out First Second Third
Program Name Is: ./a.out
Number Of Arguments Passed: 4
----Following Are The Command Line Arguments Passed----
argv[0]: ./a.out
argv[1]: First
argv[2]: Second
argv[3]: Third
3. Single Argument : When the above code is compiled and executed with a single argument
separated by space but inside double quotes, it produces the following output.
$ ./a.out "First Second Third"
Program Name Is: ./a.out
Number Of Arguments Passed: 2
----Following Are The Command Line Arguments Passed----
argv[0]: ./a.out
argv[1]: First Second Third
4. Single argument in quotes separated by space : When the above code is compiled and executed
with a single argument separated by space but inside single quotes, it produces the following
output.
Page 22 of 30
Programming for Problem Solving Using ‘C’ Unit-V
argv[0]: ./a.out
argv[1]: First Second Third
Preprocessor Directives
In C programming language, preprocessor directive is a step performed before the actual source code
compilation. It is not part of the compilation. Preprocessor directives in C programming language are
used to define and replace tokens in the text and also used to insert the contents of other files into the
source file.
When we try to compile a program, preprocessor commands are executed first and then the program
gets compiled.
Every preprocessor command begins with # symbol. We can also create preprocessor commands with
parameters.
Below is the list of preprocessor directives that C programming language offers.
Syntax/Description
Preprocessor
Syntax: #define
This macro defines constant value and can be any of
Macro the basic data types.
Page 23 of 30
Programming for Problem Solving Using ‘C’ Unit-V
A program in C language involves into different processes. Below diagram will help you to understand
all the processes that a C program comes across.
All preprocessor commands begin with a hash symbol (#). It must be the first nonblank character, and
for readability, a preprocessor directive should begin in the first column. The following section lists
down all the important preprocessor directives −
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
Page 24 of 30
Programming for Problem Solving Using ‘C’ Unit-V
10 #error
Prints error message on stderr.
11 #pragma
Issues special commands to the compiler, using a standardized method.
Page 25 of 30
Programming for Problem Solving Using ‘C’ Unit-V
#include <stdio.h>
#define height 100
#define number 3.14
#define letter 'A'
#define letter_sequence "ABC"
#define backslash_char '\?'
void main()
{
printf("value of height : %d \n", height );
printf("value of number : %f \n", number );
printf("value of letter : %c \n", letter );
printf("value of letter_sequence : %s \n", letter_sequence);
printf("value of backslash_char : %c \n", backslash_char);
OUTPUT:
Page 26 of 30
Programming for Problem Solving Using ‘C’ Unit-V
#include <stdio.h>
#define RAJU 100
int main()
{
#ifdef RAJU
printf("RAJU is defined. So, this line will be added in " \
"this C file\n");
#else
printf("RAJU is not defined\n");
#endif
return 0;
}
OUTPUT:
#include <stdio.h>
#define RAJU 100
int main()
{
#ifndef SELVA
{
printf("SELVA is not defined. So, now we are going to " \
"define here\n");
#define SELVA 300
}
#else
printf("SELVA is already defined in the program”);
Page 27 of 30
Programming for Problem Solving Using ‘C’ Unit-V
#endif
return 0;
OUTPUT:
#include <stdio.h>
#define a 100
int main()
{
#if (a==100)
printf("This line will be added in this C file since " \
"a \= 100\n");
#else
printf("This line will be added in this C file since " \
"a is not equal to 100\n");
#endif
return 0;
}
OUTPUT:
#include <stdio.h>
Page 28 of 30
Programming for Problem Solving Using ‘C’ Unit-V
OUTPUT:
#include <stdio.h>
void function1( );
void function2( );
#pragma startup function1
#pragma exit function2
int main( )
{
printf ( "\n Now we are in main function" ) ;
return 0;
}
void function1( )
{
printf("\nFunction1 is called before main function call");
}
void function2( )
{
printf ( "\nFunction2 is called just before end of " \ "main function" ) ;"
Page 29 of 30
Programming for Problem Solving Using ‘C’ Unit-V
OUTPUT:
X
Ramdas Kapila
Assistant Professor, NSRIT
Page 30 of 30