Mod5 Chapter3

Download as pdf or txt
Download as pdf or txt
You are on page 1of 25

Unit 3 : Files

Stream
What's a stream?
A stream is basically a sequence of data. Whatever data we use in our programming
flows through a stream. A stream can be thought of as a channel connecting a
processor or logic unit (where data is processed according to the instructions) and
input and output devices.
A stream is a popular concept for how to do input/output. Basically, a stream
is a sequence of characters with functions to take characters out of one end, and put
characters into the other end. In the case of input/output streams, one end of the
stream is connected to a physical I/O device such as a keyboard or display. If it is a
console output stream, your program puts characters into one end of the stream, and
the display system takes characters out of the other and puts them on the screen. If
it is a console input stream, the keyboard puts characters into one end of the stream,
and your program takes characters out of the other and stores the results in variables
in the program.
If no characters are waiting in the input stream, your program must wait until
you supply some by typing on the keyboard. File streams follow the same principle,
except that the file system is attached to the other end of the stream. The Standard
I/O streams: stdin and stdout Two streams exist to allow you to communicate with
your "console" - the screen and keyboard setup that makes up the traditional
computer user interface. These are the input stream stdin (console input), which is
connected to the keyboard, and the output stream stdout (console output), which is
connected to your display.
These two streams are created when the system starts your program. To use
stdin and stdout and the input and output functions for them, you have to tell the
compiler about them by including the relevant declarations in the library header file:
#include When your program is linked, the relevant library object modules must be
included - usually this is automatic or a normal part of your compilation/linking
process. The streams stdin and stdout are actually global variables that are declared
in and initialized during program startup. This document uses stdin and stdout for
examples, but everything herein works for any other text input or output stream, such
as one your program might create itself for disk file input/output. The C Standard
Library includes a variety of functions for doing input/output
Stream Output
The printf function The C Standard Library function printf allows you to output
values of variables using a specified format for each one. The value of the variable
is converted into a sequence of characters depending on the format, and these
characters are inserted into the output stream for transmission to the output device.
For example: int int_var = 123; printf("%d", int_var); The variable int_var is an
integer containing the binary value for 123. The printf function sees the formatting
item %d and uses it as an instruction to interpret the bit pattern in the first variable
listed (int_var) as an integer to be output in decimal notation. It will then construct
the sequence of characters '1' , '2', and '3' and insert them into the output stream. The
printf function uses a set of default formatting rules for each formatting item type

Stream Input
The scanf function The scanf function scans the content of the input stream, looking
for the items specified by a format string, and storing them in the addresses provided
as arguments. The formatting string is similar to printf's. For example, "%d"
specifies that a decimal integer should be scanned for. Like printf, scanf lacks type
safety; there is no required check that the types specified by your format string match
the addresses for storage that you provide. However, input is more complicated than
output, because the user might make 3 typing mistakes that keep scanf from finding
what you intend. So your code must take into account when scanf might fail, and
deal with it.
How scanf function works
The prototype for the scanf function is int scanf. The char * parameter is the format
string, and the ... is a special type declaration that tells the compiler that any number
of arguments of any type can appear before the right parentheses; the compiler
responds by simply pushing the number of arguments that are actually present onto
the function call stack followed by a copy of every argument value. It is assumed
that the arguments are addresses (pointers) where values can be stored, and that the
pointed-to locations are the same types in the same order as specified in the format
string.
In general, scanf works as follows:
1. If there are no characters waiting in the input stream, scanf waits until the system
says there are characters ready to be read. This is an important point: normally, the
system lets the user type characters, and saves them without letting the program see
them. This is to give the user a chance to backspace and correct any typing errors.
When the user is finishing typing, he or she signals that the input is ready to be
processed by hitting the Carriage Return (or Return) key. The system then allows
scanf to start processing the input.
2. Then scanf examines the formatting string. Each % item is a request to look for a
value of a certain type and representation in the input stream. In almost all cases, the
scanf function starts the scan for the value by skipping over any initial whitespace
characters. Whitespace characters are characters like space, newline (e.g. return), or
tab - when typed or displayed, their effect is simply to make some "white space"
between other characters. Then scanf tries to find a sequence of characters that
satisfies the % item specification. It goes as far as it can in the input, and stops when
the request is satisfied, or if it encounters a character that indicates the end of the
desired input.
3. All characters skipped or used to satisfy the request are "consumed" and removed
from the stream. The next input operation will start with the first character that was
not used.
Let's start with a simple example:
int int_var; int result;
result = scanf("%d", &int_var);

FILES
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
When dealing with files, there are two types of files you should know about:
• Text files
• 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 it 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.

File Operations
In C, you can perform four major operations on files, either text or binary:
• Creating a new file
• Opening an existing file
• Closing a file
• Reading from and writing information to a file

Opening a file - for creation and edit


Opening a file is performed using the fopen() function defined in the stdio.h header
file.
The syntax for opening a file in standard I/O is:
ptr = fopen("fileopen","mode");
For example,
fopen("E:\\cprogram\\newprogram.txt","w");
fopen("E:\\cprogram\\oldprogram.bin","rb");
Let's suppose the file newprogram.txt doesn't exist in the location E:\cprogram. The
first function creates a new file named newprogram.txt and opens it for writing as
per the mode 'w'.
The writing mode allows you to create and edit (overwrite) the contents of the file.
Now let's suppose the second binary file oldprogram.bin exists in the location
E:\cprogram. The second function opens the existing file for reading in binary mode
'rb'.
The reading mode only allows you to read the file, you cannot write into the file.
Closing a File
The file (both text and binary) should be closed after reading/writing.
Closing a file is performed using the fclose() function.
fclose(fptr);
Here, fptr is a file pointer associated with the file to be closed.
Reading and writing to a text file
For reading and writing to a text file, we use the functions fprintf() and fscanf().
They are just the file versions of printf() and scanf(). The only difference is that
fprintf() and fscanf() expects a pointer to the structure FILE.

Reading and writing to a text file


For reading and writing to a text file, we use the functions fprintf() and fscanf().
They are just the file versions of printf() and scanf(). The only difference is that
fprintf() and fscanf() expects a pointer to the structure FILE.
Other functions like fgetchar(), fputc() etc. can be used in a similar way.

Reading and writing to a binary file


Functions fread() and fwrite() are used for reading from and writing to a file on the
disk respectively in case of binary files.

Writing to a binary file


To write into a binary file, you need to use the fwrite() function. The functions take
four arguments:
• address of data to be written in the disk
• size of data to be written in the disk
• number of such type of data
• pointer to the file where you want to write.
fwrite(addressData, sizeData, numbersData, pointerToFile);

Reading from a binary file


Function fread() also take 4 arguments similar to the fwrite() function as above.
fread(addressData, sizeData, numbersData, pointerToFile);
Getting data using fseek()
If you have many records inside a file and need to access a record at a specific
position, you need to loop through all the records before it to get the record.
This will waste a lot of memory and operation time. An easier way to get to the
required data can be achieved using fseek().
As the name suggests, fseek() seeks the cursor to the given record in the file.
Syntax of fseek()
fseek(FILE * stream, long int offset, int whence);
The first parameter stream is the pointer to the file. The second parameter is the
position of the record to be found, and the third parameter specifies the location
where the offset starts.

Different whence in fseek()


Whence Meaning
SEEK_SET Starts the offset from the beginning of the file.
SEEK_END Starts the offset from the end of the file.
SEEK_CUR Starts the offset from the current location of the cursor in the file.

Formatted I/O Functions

Formatted I/O functions are used to take various inputs from the user and display
multiple outputs to the user. These types of I/O functions can help to display the
output to the user in different formats using the format specifiers. These I/O supports
all data types like int, float, char, and many more.

Why they are called formatted I/O?


These functions are called formatted I/O functions because we can use format
specifiers in these functions and hence, we can format these functions according to
our needs.
List of some format specifiers-
S NO.Format Specifier Type Description
1 %d int/signed int for I/O signed integer value
2 %c char for I/O character value
3 %f float for I/O decimal floating-point value
4 %s string for I/O string/group of characters
5 %ld int for I/O long signed integer value
6 %u unsigned int for I/O unsigned integer value
7 %i unsigned int for the I/O integer value
8 %lf double for I/O fractional or floating data
9 %n prints nothing

The following formatted I/O functions will be discussed in this section-


printf()
scanf()
sprintf()
sscanf()

printf():
printf() function is used in a C program to display any value like float, integer,
character, string, etc on the console screen. It is a pre-defined function that is already
declared in the stdio.h(header file).

// C program to implement
// printf() function
#include <stdio.h>

// Driver code
int main()
{
// Declaring an int type variable
int a;
// Assigning a value in a variable
a = 20;

// Printing the value of a variable


printf("%d", a);

return 0;
}
Output
20

Syntax 2:
To display any string or a message
printf(“Enter the text which you want to display”);

scanf():

scanf() function is used in the C program for reading or taking any value from the
keyboard by the user, these values can be of any data type like integer, float,
character, string, and many more. This function is declared in stdio.h(header file),
that’s why it is also a pre-defined function. In scanf() function we use &(address-of
operator) which is used to store the variable value on the memory location of that
variable.

Syntax:
scanf(“Format Specifier”, &var1, &var2, …., &varn);
Example:
// C program to implement
// scanf() function
#include <stdio.h>

// Driver code
int main()
{
int num1;

// Printing a message on
// the output screen
printf("Enter a integer number: ");

// Taking an integer value


// from keyboard
scanf("%d", &num1);
// Displaying the entered value
printf("You have entered %d", num1);

return 0;
}

Output
Enter a integer number: You have entered 0
Output:
Enter a integer number: 56
You have entered 56

sprintf():

sprintf stands for “string print”. This function is similar to printf() function but this
function prints the string into a character array instead of printing it on the console
screen.
Syntax:
sprintf(array_name, “format specifier”, variable_name);

// C program to implement
// the sprintf() function
#include <stdio.h>

// Driver code
int main()
{
char str[50];
int a = 12, b = 18;

// The string "2 and 8 are even number"


// is now stored into str
sprintf(str, "%d and %d are even number",
a, b);

// Displays the string


printf("%s", str);
return 0;
}
Output
12 and 18 are even number
sscanf():

sscanf stands for “string scanf”. This function is similar to scanf() function but this
function reads data from the string or character array instead of the console screen.

Syntax:
sscanf(array_name, “format specifier”, &variable_name);
Example:

// C program to implement
// sscanf() function
#include <stdio.h>

// Driver code
int main()
{
char str[50];
int a = 2, b = 8, c, d;

// The string "a = 2 and b = 8"


// is now stored into str
// character array
sprintf(str, "a = %d and b = %d",
a, b);

// The value of a and b is now in


// c and d
sscanf(str, "a = %d and b = %d",
&c, &d);

// Displays the value of c and d


printf("c = %d and d = %d", c, d);
return 0;
}
Output
c = 2 and d = 8
Unformatted Input/Output functions

Unformatted I/O functions are used only for character data type or character
array/string and cannot be used for any other datatype. These functions are used to
read single input from the user at the console and it allows to display the value at the
console.

Why they are called unformatted I/O?

These functions are called unformatted I/O functions because we cannot use format
specifiers in these functions and hence, cannot format these functions according to
our needs.

The following unformatted I/O functions will be discussed in this section-

• getch()
• getche()
• getchar()
• putchar()
• gets()
• puts()
• putch()

getch():

getch() function reads a single character from the keyboard by the user but doesn’t
display that character on the console screen and immediately returned without
pressing enter key. This function is declared in conio.h(header file). getch() is also
used for hold the screen.
Syntax:
getch(); or variable-name = getch();

Example:
// C program to implement
// getch() function
#include <conio.h>
#include <stdio.h>

// Driver code
int main()
{
printf("Enter any character: ");

// Reads a character but


// not displays
getch();

return 0;
}
Output:

Enter any character:

getche():

getche() function reads a single character from the keyboard by the user and displays
it on the console screen and immediately returns without pressing the enter key. This
function is declared in conio.h(header file).
Syntax:
getche(); or variable_name = getche();

Example:
// C program to implement
// the getche() function
#include <conio.h>
#include <stdio.h>

// Driver code
int main()
{
printf("Enter any character: ");

// Reads a character and


// displays immediately
getche();
return 0;
}
Output:

Enter any character: h


getchar():

The getchar() function is used to read only a first single character from the keyboard
whether multiple characters is typed by the user and this function reads one character
at one time until and unless the enter key is pressed. This function is declared in
stdio.h(header file)
Syntax: Variable-name = getchar();
Example:
// C program to implement
// the getchar() function
#include <conio.h>
#include <stdio.h>

// Driver code
int main()
{
// Declaring a char type variable
char ch;

printf("Enter the character: ");

// Taking a character from keyboard


ch = getchar();

// Displays the value of ch


printf("%c", ch);
return 0;
}
Output:
Enter the character: a

putchar():

The putchar() function is used to display a single character at a time by passing that
character directly to it or by passing a variable that has already stored a character.
This function is declared in stdio.h(header file)
Syntax:
putchar(variable_name);
Example:
// C program to implement
// the putchar() function
#include <conio.h>
#include <stdio.h>
// Driver code
int main()
{
char ch;
printf("Enter any character: ");

// Reads a character
ch = getchar();

// Displays that character


putchar(ch);
return 0;
}
Output:
Enter any character: Z

gets():

gets() function reads a group of characters or strings from the keyboard by the user
and these characters get stored in a character array. This function allows us to write
space-separated texts or strings. This function is declared in stdio.h(header file).
Syntax: char str[length of string in number]; //Declare a char type variable of any
length
gets(str);

Example:
// C program to implement
// the gets() function
#include <conio.h>
#include <stdio.h>

// Driver code
int main()
{
// Declaring a char type array
// of length 50 characters
char name[50];

printf("Please enter some texts: ");

// Reading a line of character or


// a string
gets(name);

// Displaying this line of character


// or a string
printf("You have entered: %s",
name);
return 0;
}
Output:

Please enter some texts: HELLO World


You have entered: HELLO World

puts():

In C programming puts() function is used to display a group of characters or strings


which is already stored in a character array. This function is declared in
stdio.h(header file).
Syntax:
puts(identifier_name );
Example:
// C program to implement
// the puts() function
#include <stdio.h>

// Driver code
int main()
{
char name[50];
printf("Enter your text: ");
// Reads string from user
gets(name);
printf("Your text is: ");
// Displays string
puts(name);

return 0;
}
Output:

Enter your text:Good Morning


Your text is: Good Morning
putch():

putch() function is used to display a single character which is given by the user and
that character prints at the current cursor location. This function is declared in
conio.h(header file)
Syntax:
putch(variable_name);
Example:
// C program to implement
// the putch() functions
#include <conio.h>
#include <stdio.h>

// Driver code
int main()
{
char ch;
printf("Enter any character:\n ");

// Reads a character from the keyboard


ch = getch();

printf("\nEntered character is: ");

// Displays that character on the console


putch(ch);
return 0;
}
Output:
Enter any character:
Entered character is: d

File Status Functions


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.

o Creation of the new file


o Opening an existing file
o Reading from the file
o Writing to the file
o Deleting the file

Functions for file handling


There are many functions in the C library to open, read, write, search and close the
file. A list of file functions are given below:
fopen:

C fopen is a C library function used to open an existing file or create a new file.

The basic format of fopen is:

Syntax:
FILE *fopen( const char * filePath, const char * mode );

Parameters

• filePath: The first argument is a pointer to a string containing the name of


the file to be opened.
• mode: The second argument is an access mode.

C fopen function returns NULL in case of a failure and returns a FILE stream
pointer on success.

Example:
#include<stdio.h>

int main()
{
FILE *fp;
fp = fopen("fileName.txt","w");
return 0;
}

• The above example will create a file called fileName.txt.


• The w means that the file is being opened for writing, and if the file does not
exist then the new file will be created.

Fclose:

fclose() function is C library function and it's used to releases the memory stream,
opened by fopen() function.

The basic format of fclose is:

Syntax:
int fclose( FILE * stream );

Return Value

C fclose returns EOF in case of failure and returns 0 on success.


Example:
#include<stdio.h>

int main()
{
FILE *fp;
fp = fopen("fileName.txt","w");
fprintf(fp, "%s", "Sample Texts");
fclose(fp);
return 0;
}

• The above example will create a file called fileName.txt.


• The w means that the file is being opened for writing, and if the file does not
exist then the new file will be created.
• The fprintf function writes Sample Texts text to the file.
• The fclose function closes the file and releases the memory stream.

Getc();

getc() function is the C library function, and it's used to read a character from a file
that has been opened in read mode by fopen() function.

Syntax:
int getc( FILE * stream );

Return Value

• getc() function returns the next requested object from the stream on success.
• Character values are returned as an unsigned char cast to an int or EOF on
the end of the file or error.
• The function feof() and ferror() to distinguish between end-of-file and error
must be used.

Example:
#include<stdio.h>

int main()
{
FILE *fp = fopen("fileName.txt", "r");
int ch = getc(fp);
while (ch != EOF)
{
//To display the contents of the file on the screen
putchar(ch);
ch = getc(fp);
}

if (feof(fp))
printf("\n Reached the end of file.");
else
printf("\n Something gone wrong.");
fclose(fp);

getchar();
return 0;
}

Putc()

putc() function is C library function, and it's used to write a character to the
file. This function is used for writing a single character in a stream along with that
it moves forward the indicator's position.

Syntax:
int putc( int c, FILE * stream );
Example:
int main (void)
{
FILE * fileName;
char ch;
fileName = fopen("anything.txt","wt");
for (ch = 'D' ; ch <= 'S' ; ch++) {
putc (ch , fileName);
}
fclose (fileName);
return 0;
}

Fprintf

C fprintf function pass arguments according to the specified format to the file
indicated by the stream. This function is implemented in file related programs for
writing formatted data in any file.

Syntax:
int fprintf(FILE *stream, const char *format, ...)
Example:
int main (void)
{
FILE *fileName;
fileName = fopen("anything.txt","r");
fprintf(fileName, "%s %s %d", "Welcome", "to", 2018);
fclose(fileName);
return(0);
}

Fscanf

C fscanf function reads formatted input from a file. This function is implemented
in file related programs for reading formatted data from any file that is specified in
the program.

Syntax:
int fscanf(FILE *stream, const char *format, ...)
Its return the number of variables that are assigned values, or EOF if no
assignments could be made.

Example:
int main()
{
char str1[10], str2[10];
int yr;
FILE* fileName;
fileName = fopen("anything.txt", "w+");
fputs("Welcome to", fileName);
rewind(fileName);
fscanf(fileName, "%s %s %d", str1, str2, &yr);
printf("----------------------------------------------- \n");
printf("1st word %s \t", str1);
printf("2nd word %s \t", str2);
printf("Year-Name %d \t", yr);
fclose(fileName);
return (0);
}

Fgets

C fgets function is implemented in file related programs for reading strings from
any particular file. It gets the strings 1 line each time.
Syntax:
char *fgets(char *str, int n, FILE *stream)
Example:
void main(void)
{
FILE* fileName;
char ch[100];
fileName = fopen("anything.txt", "r");
printf("%s", fgets(ch, 50, fileName));
fclose(fileName);
}

• On success, the function returns the same str parameter


• C fgets function returns a NULL pointer in case of a failure.

Fputs

C fputs function is implemented in file related programs for writing string to any
particular file.

Syntax:
int fputs(const char *str, FILE *stream)
Example:
#include<stdio.h>
int main()
{
FILE *fp;
fp = fopen("fileName.txt","w");

fputs("This is a sample text file.", fp);


fputs("This file contains some sample text data.", fp);

fclose(fp);
return 0;
}
In this function returns non-negative value, otherwise returns EOF on error.
File Positioning functions

• When doing reads and writes to a file, the OS keeps the track of where your in the
file using a counter, generally known as file pointer.
• The following are the functions in access file at random.
• ftell(): Tells the current position of the file pointer.
• fseek(): To position a file pointer at a desired place.
• Rewind(): Resets the file pointer to the beginning of the file.

You might also like