Streams
Standard Streams
General Definition
• As a verb, stream means to flow in a continuous or steady manner,
like a liquid.
In C programming
• A stream is a logical abstraction that represents a flow of data
between a program and an input/output (I/O) source or destination.
• It provides a consistent interface for handling data transfer, regardless
of the underlying physical device or media.
Types of streams
1. Standard Streams: Readily available streams
2. File streams: Associated with files on disk
3. Network streams: Associated with network connections
4. Memory streams: Associated with data in memory
Standard Streams
• Three predefined streams that are automatically available to every program
when it starts execution
standard input standard output standard error
Usually connected to the Also typically
Typically connected
console (the user's screen) connected to the
to the keyboard
console
to receive input used specifically for
from the user. to display output error messages and
diagnostic output.
printf(), putchar(), and
scanf(), getchar(), gets() fprintf(stderr, ...)
puts()
File Streams
• File streams are a fundamental concept in C programming that
provide a high-level abstraction for interacting with files.
• They act as a bridge between your program and the physical files
stored on your computer, simplifying the process of reading and
writing data.
Text and Binary Files
Text Binary
A sequence of characters interpreted A continuous sequence of bytes without
Definition and organized as lines terminated by any specific structure or interpretation.
newline characters (\n).
Purpose Designed for raw data like images,
Designed for human-readable text
audio, or executables.
Organization Data organized into lines for Data treated as a continuous stream
readability. of bytes, no line breaks.
Less efficient for raw binary data due More efficient for raw binary data
Efficiency to potential interpretations. due to direct byte-level access.
Functions fgets(), fputs(), fprintf(), fscanf() fread(), fwrite()
• All variables created by a program are stored in RAM.
• No variable stays on even after the end of program.
• Similarly, the contents of memory are wiped out when the computer
is powered off
• Whatever data you have read or modified is gone.
Solution
•Files
• A file is a collection of data stored in one unit, identified by a filename.
• File is stored in secondary memory: Hard Disk, CD, USB etc…
• Permanent memory
• We can save data into files (file writing)
• We can read data from files (file reading)
• We can add new data to existing files (file appending)
Files and Memory
• Memory allocation for files is done by Operating System.
• The allocated memory may not be contiguous physically. But it is
logically contiguous.
• We may treat this as contiguous memory.
• Last byte of a text file is a special character called “EOF”
• This can be used to check if we have reached the end of file.
File Pointer
• Also known as a file stream pointer, is a special variable that acts as a
link between your program and a physical file on disk.
• It provides a way to interact with the file's contents for reading,
writing, or other operations.
• Declaration: using FILE type
• FILE *fptr;
• //This statement declares the file pointer of the name fptr.
Working with files in C
1. File Association: This establishes a connection between your
program and the data in the file.
2. Data flow: Standard I/O functions like fread() and fwrite() to read
data from the file into your program, or write data from your
program into the file.
3. Stream operations: Seeking a Specific position on a file, checking
for the end of file, etc.
4. End Association.
File Handling Functions in C
Functionality Functions
Association fopen, fclose
Data Flow fread, fwrite, fgets, fputs, fprintf, fscanf, fgetc,
fputc
Stream fseek(), rewind(), feof(), ferror(), ftell()
Operations
File Association
• A stream is connected to a file by opening it.
• This can be done with the function fopen()
• Using fopen() returns a pointer to an object of the type FILE.
• This is assigned to a File pointer declared in the code.
• Thus, establishing the link between the program and physical file.
File Association (contd)
• But, how we open a file varies with the intended action.
• If we wish to read data from file,
• we open the file in read mode.
• If we wish to store data from file,
• we open it in write mode.
• If we wish to add data to already existing file,
• we open it in append mode
• This information is to be passed in form of an argument.
fopen()
• Prototype:
FILE *fopen(const char *filename, const char *mode);
• Return type: A pointer to the object of type FILE
• Parameters:
• const char *filename: A string, that specifies the name of the file to
be opened.
• const char *mode: Another string, that specifies the mode in which a
file is to be opened.
fopen(): Modes of Opening
Mode of String Literal Mode of Opening String
Opening Literal
Reading “r” Read also with ability to write “r+”
Writing “w” Write also with ability to read “w+”
Appending “a” Append also with ability to read “a+”
Mode of Opening String Literal
Read byte by byte. “rb”
Write byte by byte. “wb”
Dataflow
• To enable exchange between file stream and the program.
• Functions were defined in <stdio.h>
• Some of the most commonly used such functions are:
1. fscanf(): Formatted Input Function
2. fprintf(): Formatted Output Function
3. fgets(): String Input Function
4. fputs(): String Output Function
5. fgetc(): Character Input Function
6. fputc(): Character Output Function
7. fread(): To read blocks of data from binary files.
8. fwrite(): To write blocks of data onto binary files.
fprintf()
int fprintf(FILE *stream, const char *format, ...);
• This is just like printf, the only difference is instead of writing it on
screen, we print into a file
• Format string: Both use a format string to specify how the output
should be formatted, using conversion specifiers like %d, %f, %s, etc.
• Variable arguments: Both accept a variable number of arguments
following the format string, corresponding to the values to be
formatted and printed.
• Return value: Both return the number of characters successfully
written, or a negative value if an error occurs.
fscanf()
int fscanf(FILE *stream, const char *format, ...);
• This is similar to scanf, the difference again is that we read data from files
instead of keyboard
• Stream: The file stream from which to read the data.
• format: A format string that controls how the input is interpreted. It uses
conversion specifiers (like %d, %f, %s, etc.) to match different data types.
• ...: Variable number of arguments representing the variables where the
scanned values will be stored.
• Returns the number of items successfully read and assigned, or EOF if an
error or end-of-file occurs.
fgets()
char *fgets(char *str, int size, FILE *stream);
• str: Pointer to buffer to store the line
• size: Maximum number of characters to read (including null
terminator)
• stream: File stream to read from
• Reads from the file fp into str until any one of these happens
• No. of characters read = size - 1
• \n is read (the char \n is added to str)
• EOF is reached or an error occurs
• ‘\0’ added at end of str if no error
• Returns NULL on error or EOF, otherwise returns a character pointer.
fputs()
int fputs(const char *str, FILE *stream);
• str: String to write to the file
• stream: File stream to write to
• Returns: Returns non-negative integer on success, EOF on error
fgetc()
int fgetc(FILE *stream);
• stream: File stream to read from
• Returns:
• Unsigned Character (0 to 255):
• Represents the character successfully read from the file.
• EOF (End-of-File): Signals that either:
• The end of the file has been reached.
• An error occurred while reading.
fputc()
int fputc(int character, FILE *stream);
• character: Character to write to the file
• stream: File stream to write to
• Return:
• The character written (as an unsigned char): Indicates successful
writing of the character to the file.
• EOF (End-of-File): Signals an error during the writing process.
Create a Text file and write a message
1. Start
2. Declare a file stream pointer
FILE *fp;
3. Associate with a file of desired name (myfile)
fp=fopen(“my_file.txt”, “w”);
(You may perform NULL check and stop implementation if file was not created)
4. Write your message onto the file
fprintf(fp, “Hello, World!”);
5. End Association
fclose(fp);
6. Stop
#include <stdio.h>
int main() {
// File pointer for handling the file
FILE *fp;
// Open the file in write mode ("w" creates a new file or overwrites an existing one)
fp = fopen("my_file.txt", "w");
// Check if the file was opened successfully
if (fp == NULL) {
printf("Error opening file!\n");
return 1; // Indicate failure
}
// Write the text to the file
fprintf(fp, "Hello World\n");
// Close the file to ensure data is written and resources are released
fclose(fp);
printf("File created and text written successfully!\n");
return 0; // Indicate success
}
Reading contents from a file
This can be done in two ways:
1. Character by Character
2. Line by Line
Reading contents from a file
(Character by Character )
1. Start
2. Declare a File Pointer
FILE *fp;
3. Associate with the targeted file.
fp=fopen(“my_file.txt”, “r”);
(You must perform NULL check to ensure that the file exists and stop if it doesn’t )
4. Read the character using fgetc(), assign it ch
ch = fgetc(fp)
Print ch
5. Repeat 4 till fgetc() returns EOF
6. Stop
#include <stdio.h>
int main()
{
FILE *fp;
char ch;
// Open the file in read mode
fp = fopen("myfile.txt", "r");
// Check for errors
if (fp == NULL) {
printf("Error opening file!\n");
return 1;
}
// Read and process characters
while ((ch = fgetc(fp)) != EOF) {
printf("%c", ch);
}
fclose(fp);
return 0;}
Reading contents from a file
(Line by Line)
1. Start
2. Declare a File Pointer
FILE *fp;
3. Associate with the targeted file
fp=fopen(“my_file.txt”, “r”);
(You must perform NULL check to ensure that the file exists and stop if it doesn’t )
4. Read the first line using fgets
Print the read line as a string
5. Repeat 4 till fgets() returns a NULL pointer
6. Stop
#include <stdio.h>
int main() {
FILE *fp;
char line[255]; // Adjust buffer size if needed
// Open the file in read mode
fp = fopen("my_file.txt", "r");
// Check for errors
if (fp == NULL) {
printf("Error opening file!\n");
return 1;
}
// Read the file contents and print to console
while (fgets(line, sizeof(line), fp) != NULL) {
printf("%s", line);
}
// Close the file
fclose(fp);
return 0;}
Copying the contents of One file onto another
1. Start
2. Declare two FILE pointers (sp,dp)
FILE *sp, *dp;
3. Associate sp with target file and dp with the desire file name.
sp = fopen("source_file.txt", "r");
dp = fopen("destination_file.txt", "w");
4. Read the contents of sp (Char by Char) store it in dp.
char ch;
while ((ch = fgetc(sp)) != EOF) { fputc(ch, dp); }
5. Repeat till the end of source file
6. Close sp,dp
fclose(sp); fclose(dp);
7. Stop
Copying the contents of One file onto another
1. Start
2. Declare two FILE pointers (sp,dp)
FILE *sp, *dp;
3. Associate sp with target file and dp with the desire file name.
sp = fopen("source_file.txt", "r");
dp = fopen("destination_file.txt", "w");
4. Read the contents of sp (line by line) store it in dp.
char buffer[100];
while (fgets(buffer, sizeof(buffer), sp) != NULL) { fputs(buffer, dp); }
5. Repeat till the end of source file
6. Close sp,dp
fclose(sp); fclose(dp);
7. Stop
Try on your own
1. Append contents of one file onto another.
2. Write a C program that reads the contents of a file and display them
in capital letters if they are alphabet.
3. Develop a C program to count the number of characters in a file.
Binary Files
• Store raw bytes: Represent data directly as it's stored in
memory, without human-readable formatting.
• Efficiency: Often smaller and faster to read/write than text files.
• Structure Preservation: Preserve the exact structure of data, essential
for images, audio, executables, and custom data structures.
• Non-Portability: Might not be compatible across different systems
due to differences in data representation.
• Stored with extension .bin
fread()
size_t fread(void *ptr, size_t size, size_t count, FILE *stream);
• ptr: Pointer to buffer to store read data
• size: Size of each element to read
• count: Number of elements to read
• stream: File stream to read from
• Reads count elements of size bytes from the file fp into the memory
pointed to by ptr.
• Returns:
• The number of elements successfully read from the file
• 0 only at the end of the file.
fwrite()
size_t fwrite(const void *ptr, size_t size, size_t count, FILE *stream);
• ptr: Pointer to data to write
• size: Size of each element to write
• count: Number of elements to be written
• stream: File stream to write to
• Returns: The number of elements successfully written to the file.
Creating a Binary File
#include <stdio.h>
struct Person {
char name[50]; int branch;};
int main() {
struct Person avs = {“Deepak", 4};
// Write to binary file
FILE *fp = fopen("data.bin", "wb"); // Open in binary write mode
if (fp == NULL) {
printf("Error opening file!\n");
exit(1);
}
fwrite(&avs, sizeof(struct Person), 1, fp);
fclose(fp);
#include <stdio.h>
struct Person {
Reading from a Binary
char name[50]; int branch;}; File
int main() {
// Read from binary file
FILE *fp;
fp = fopen("data.bin", "rb"); // Open in binary read mode
if (fp == NULL) {
printf("Error opening file!\n");
return 1;
}
struct Person person2;
fread(&person2, sizeof(struct Person), 1, fp);
fclose(fp);
// Display the read data
printf("Name: %s\n", person2.name);
printf("Branch: %d\n", person2.branch);
return 0;}
Stream Operations
• These are special purpose functions to handle streams in C.
• Some of most commonly used such functions are :
1. fseek()
2. ftell()
3. feof()
4. ferror()
5. rewind()
fseek()
int fseek(FILE *stream, long offset, int origin)
• offset: Distance to move from the origin (positive/negative values)
• Positive: Forward Shift
• Negative: Backward shift
• origin: Starting point for the offset (SEEK_SET, SEEK_CUR, SEEK_END)
• SEEK_SET: Beginning of the file (offset from the start)
• SEEK_CUR: Current position of the file pointer (offset from current location)
• SEEK_END: End of the file (offset from the end)
• Return: 0 on success and non zero value on error
ftell()
long ftell(FILE *stream)
• Retrieves the current position of the file pointer within the file
pointed by stream.
• Return Value: long value representing the current position of file
pointer.
feof()
int feof(FILE *stream)
• Checks if the end-of-file condition has been reached for the specified
stream.
• Return: non-zero if end-of-file reached, 0 otherwise.
ferror()
int ferror(FILE *stream)
• Checks if an error has occurred on the specified stream.
• Return: non-zero if an error occurred, 0 otherwise.
rewind()
void rewind(FILE *stream)
• Quickly and easily rewinds the file position indicator to the beginning
of the file.
• Syntax: No additional arguments needed.
• Return: void, doesn't return any value.
• Useful in read mode to or a+ mode, as it enables us to read the
contents from the beginning again.
Try this
• A file consists of two integers:
• Write a C program to add those numbers and store the result in the same file.