MCT-242L CP (Fall2022) - Lab 20 - File Input, Output
MCT-242L CP (Fall2022) - Lab 20 - File Input, Output
OBJECTIVE:
This lab will introduce basic File Input/Output concepts in a C Language Program. At the end of this lab, you
should be able to:
APPARATUS:
• Laptop\PC with following tools installed
o Visual Studio Code with C/C++ and Code Runner Extensions
o C/C++ mingw-w64 tools for Windows 10
When we say Output, it means to display some data on screen, printer, or in any file. C programming provides
a set of built-in functions to output the data on the computer screen as well as to save it in text or binary files.
C programming treats all the devices as files. Standard File File Pointer Device
So, devices such as the display are addressed Standard Input stdin Keyboard
in the same way as files and the following Standard Output stdout Screen
three files are automatically opened when a Standard Error stderr Screen
program executes to provide access to the keyboard and screen.
The file pointers are the means to access the file for reading and writing purpose. This section explains how
to read values from the screen and how to print the result on the screen.
The int getchar(void) function reads the next available character from the screen and returns it as an
integer. 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.
The int putchar(int c) function puts the passed character on the screen and returns the same character.
This function puts only single character at a time. You can use this method in the loop in case you want to
display more than one character on the screen.
#include <stdio.h>
int main()
{
int c;
return 0;
}
// End of program
Enter a value >> Example_20_1.c
Program Output
You entered = E
When the above code is compiled and executed, it waits for you to input some text. When you enter a text
and press enter, then the program proceeds and reads only a single character and displays it.
The char *gets(char *s) function reads a line from stdin into the buffer pointed to by s until either a
terminating newline or EOF (End of File).
The int puts(const char *s) function writes the string ‘s’ and a trailing newline to stdout.
----------------------------------------------------------------
Written by Shujat Ali ([email protected]) on 04-Dec-2021.
IDE: Visual Studio Code 1.60.0
C Compiler: GCC (Rev. 5, Built by MSYS2 Project) 10.3.0 */
#include <stdio.h>
int main()
{
char str[100];
return 0;
}
// End of program
Enter a value >> Example_20_2.c
Program Output
You entered = Example_20_2.c
When the above code is compiled and executed, it waits for you to input some text. When you enter a text
and press enter, then the program proceeds and reads the complete line till end and displays it.
The int scanf(const char *format, ...) function reads the input from the standard input stream stdin
and scans that input according to the format provided.
The int printf(const char *format, ...) function writes the output to the standard output stream
stdout and produces the output according to the format provided.
The format can be a simple constant string, but you can specify %s, %d, %c, %f, etc., to print or read strings,
integer, character, or float, respectively. There are many other formatting options available which can be
used based on requirements.
Let us now proceed with a simple example to understand the concepts better:
Example 20.3: Read/Write Multiple Values
/* Example_20_3.c: Read/Write Multiple Values
----------------------------------------------------------------
This program demonstrates the use of scanf() and printf()
functions that are used to read/write multiple values in C.
----------------------------------------------------------------
Written by Shujat Ali ([email protected]) on 04-Dec-2021.
IDE: Visual Studio Code 1.60.0
#include <stdio.h>
int main()
{
char str[100];
int i;
return 0;
}
// End of program
Enter a value >> lucky_number 7
Program Output
You entered = lucky_number 7
When the above code is compiled and executed, it waits for you to input some text. When you enter a text
and press enter, then program proceeds and reads the input and displays it.
Here, it should be noted that scanf() expects input in the same format as you provided %s and %d, which
means you must provide valid inputs like "string integer". If you provide "string string" or "integer integer",
then it will be assumed as wrong input. Secondly, while reading a string, scanf() stops reading as soon as it
encounters a space, so "this is test" are three strings for scanf().
A file represents a sequence of bytes, regardless of it being a text file or a binary file. C programming language
provides access on high-level functions as well as low-level (OS level) calls to handle file on your storage
devices. This section will take you through the important calls for file management.
Opening Files
You can use the fopen() function to create a new file or to open an existing file. This call will initialize an
object of the type FILE, which contains all the information necessary to control the stream. The prototype of
this function call is as follows:
Here, filename is a string literal, which you will use to name your file, and access mode can have one of the
following values.
Mode Description
"r" Opens an existing text file for reading purpose.
Opens a text file for writing. If it does not exist, then a new file is created. Here your program
"w"
will start writing content from the beginning of the file.
Opens a text file for writing in appending mode. If it does not exist, then a new file is created.
"a"
Here your program will start appending content in the existing file content.
"r+" Opens a text file for both reading and writing.
Opens a text file for both reading and writing. It first truncates the file to zero length if it exists,
"w+"
otherwise creates a file if it does not exist.
Opens a text file for both reading and writing. It creates the file if it does not exist. The reading
"a+"
will start from the beginning, but writing can only be appended.
If you are going to handle binary files, then you will use the following access modes instead of the above-
mentioned ones:
Closing a File
To close a file, use the fclose() function. The prototype of this function is:
The fclose() function returns zero on success, or EOF if there is an error in closing the file. This function
flushes any data still pending in the buffer to the file, closes the file, and releases any memory used for the
file. The EOF is a constant defined in the header file stdio.h.
There are various functions provided by C standard library to read and write a file, character by character, or
in the form of a fixed length string.
Writing a File
The function fputc() writes the character value of the argument c to the output stream referenced by fp. It
returns the written character written on success otherwise EOF if there is an error. You can use the following
functions to write a null-terminated string to a stream:
You can use int fprintf(FILE *fp,const char *format, ...) function as well to write a string into a
file. Try the following example.
Example 20.4: Writing a Text File
/* Example_20_4.c: Writing a Text File
----------------------------------------------------------------
This program demonstrates the use of fputs() and fprintf()
functions that are used to write to a text file in C.
----------------------------------------------------------------
Written by Shujat Ali ([email protected]) on 04-Dec-2021.
IDE: Visual Studio Code 1.60.0
C Compiler: GCC (Rev. 5, Built by MSYS2 Project) 10.3.0 */
#include <stdio.h>
int main()
{
FILE *fp;
return 0;
}
// End of program
When the above code is compiled and executed, it creates a new file test.txt in same directory and writes two
lines using two different functions. Let us now read this text file.
Reading a File
Given below is the simplest function to read a single character from a file:
The fgetc() function reads a character from the input file referenced by fp. The return value is the character
read, or in case of any error, it returns EOF. The following function allows to read a string from a stream:
If this function encounters a newline character '\n' or the end of the file EOF before they have read the
maximum number of characters, then it returns only the characters read up to that point including the new
line character.
You can also use int fscanf(FILE *fp, const char *format, ...) function to read strings from a file,
but it stops reading after encountering the first space character.
#include <stdio.h>
int main()
{
FILE *fp;
char buff[255];
fclose(fp);
return 0;
}
// End of program
1 : This
2: is testing for fprintf...
Program Output
3: This is testing for fputs...
Let's see a little more in detail about what happened here. First, fscanf() reads just This because after that,
it encountered a space, second call is for fgets() which reads the remaining line till it encountered end of
line. Finally, the last call fgets() reads the second line completely.
There are two functions that can be used for binary input and output:
Both functions should be used to read or write blocks of memories - usually arrays or structures.
TASK 20.1: Count the Characters, Words, & Lines [2 points]
Write a program that counts the number of text lines in given text file.
In main(), user must ask for the file name for which count of number
lines is required. For Lab_20.txt file, sample output is given below.
Enter the file name >> Lab_20.txt