Mod5 Chapter3
Mod5 Chapter3
Mod5 Chapter3
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
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.
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;
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: ");
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;
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;
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.
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.
• 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: ");
return 0;
}
Output:
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: ");
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;
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();
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];
puts():
// 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:
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 ");
C fopen is a C library function used to open an existing file or create a new file.
Syntax:
FILE *fopen( const char * filePath, const char * mode );
Parameters
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;
}
Fclose:
fclose() function is C library function and it's used to releases the memory stream,
opened by fopen() function.
Syntax:
int fclose( FILE * stream );
Return Value
int main()
{
FILE *fp;
fp = fopen("fileName.txt","w");
fprintf(fp, "%s", "Sample Texts");
fclose(fp);
return 0;
}
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);
}
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");
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.