0% found this document useful (0 votes)
30 views

MCT-242L CP (Fall2022) - Lab 20 - File Input, Output

The document discusses file input/output in C language. It explains standard input/output streams and functions like getchar(), putchar(), gets(), puts(), scanf(), printf() for reading and writing single characters, strings and multiple values. It also covers opening, reading and writing files using functions like fopen() and different file access modes.

Uploaded by

shoaib
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
30 views

MCT-242L CP (Fall2022) - Lab 20 - File Input, Output

The document discusses file input/output in C language. It explains standard input/output streams and functions like getchar(), putchar(), gets(), puts(), scanf(), printf() for reading and writing single characters, strings and multiple values. It also covers opening, reading and writing files using functions like fopen() and different file access modes.

Uploaded by

shoaib
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

Department of Mechatronics and Control Engineering

University of Engineering and Technology Lahore

LAB 20: FILE INPUT/OUTPUT IN C LANGAUGE


MCT-242L: Computer Programming-I Lab (Fall-2022)

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:

• Explain and use standard Input/Output


• Read/write text files

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

INPUT AND OUTPUT


When we say Input, it means to feed some data into a program. An input can be given in the form of a file or
from the command line. C programming provides a set of built-in functions to read the given input and feed
it to the program as per requirement.

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.

The Standard 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 getchar() and putchar() Functions

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.

1|Page Computer Programming-I Lab


Department of Mechatronics and Control Engineering
University of Engineering and Technology Lahore

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.

Check the following example:


Example 20.1: Read/Write Single Character
/* Example_20_1.c: Read/Write Single Character
----------------------------------------------------------------
This program demonstrates the use of getchar() and putchar()
functions that are used to read/write single character 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()
{
int c;

printf( "Enter a value >> ");


c = getchar( );
printf( "You entered = ");
putchar( 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 gets() and puts() Functions

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.

Example 20.2: Read/Write Single Line


/* Example_20_2.c: Read/Write Single Line
----------------------------------------------------------------
This program demonstrates the use of gets() and puts() functions
that are used to read/write single line in C.

2|Page Computer Programming-I Lab


Department of Mechatronics and Control Engineering
University of Engineering and Technology Lahore

----------------------------------------------------------------
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];

printf( "Enter a value >> ");


gets( str );

printf( "You entered = ");


puts( str );

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 scanf() and printf() Functions

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

3|Page Computer Programming-I Lab


Department of Mechatronics and Control Engineering
University of Engineering and Technology Lahore

C Compiler: GCC (Rev. 5, Built by MSYS2 Project) 10.3.0 */

#include <stdio.h>

int main()
{
char str[100];
int i;

printf("Enter a value >> ");


scanf("%s %d", str, &i);

printf("You entered = %s %d ", str, 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().

FILE INPUT AND OUTPUT


The last section explained the standard input and output devices handled by C programming language. This
section covers how C programmers can create, open, close text or binary files for their data storage.

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:

FILE *fopen( const char * filename, const char * mode );


Syntax to Open a File in C

4|Page Computer Programming-I Lab


Department of Mechatronics and Control Engineering
University of Engineering and Technology Lahore

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:

"rb", "wb", "ab", "rb+", "r+b", "wb+", "w+b", "ab+", "a+b"


Access Modes for Binary Files

Closing a File

To close a file, use the fclose() function. The prototype of this function is:

int fclose( FILE *fp );


Syntax to Close a File in C

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

Following is the simplest function to write individual characters to a stream:

int fputc( int c, FILE *fp );


Syntax to Write a Character a File in C

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:

5|Page Computer Programming-I Lab


Department of Mechatronics and Control Engineering
University of Engineering and Technology Lahore

int fputs( const char *s, FILE *fp );


Syntax to Write a String a File in C
The function fputs() writes the string s to the output stream referenced by fp. It returns a non-negative
value on success, otherwise EOF is returned in case of any error.

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;

// open a text file for write (+read)


fp = fopen("test.txt", "w+");

// write following lines to file


fprintf(fp, "This is testing for fprintf...\n");
fputs("This is testing for fputs...\n", fp);

// close the text file after writing


fclose(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:

int fgetc( FILE * fp );


Syntax to Read a Character a File in C

6|Page Computer Programming-I Lab


Department of Mechatronics and Control Engineering
University of Engineering and Technology Lahore

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:

char *fgets( char *buf, int n, FILE *fp );


Syntax to Read a String a File in C
The functions fgets() reads up to n - 1 characters from the input stream referenced by fp. It copies the read
string into the buffer buf, appending a null character to terminate the string.

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.

Try the following example.


Example 20.5: Reading a Text File
/* Example_20_5.c: Reading a Text File
----------------------------------------------------------------
This program demonstrates the use of fgets() and fscanf()
functions that are used to read from 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;
char buff[255];

// open a text file for read


fp = fopen("test.txt", "r");

// Read lines from text file


fscanf(fp, "%s", buff);
printf("1 : %s\n", buff );

fgets(buff, 255, (FILE*)fp);


printf("2: %s\n", buff );

fgets(buff, 255, (FILE*)fp);


printf("3: %s\n", buff );

// close the text file after writing

7|Page Computer Programming-I Lab


Department of Mechatronics and Control Engineering
University of Engineering and Technology Lahore

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.

Binary Input/Output Functions

There are two functions that can be used for binary input and output:

size_t fread(void *ptr, size_t size_of_elements, size_t number_of_elements, FILE


*a_file);

size_t fwrite(const void *ptr, size_t size_of_elements, size_t number_of_elements, FILE


*a_file);
Syntax to Read/Write Binary Files in C

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

Sample Output There are 252 characters in Lab_20.txt file


There are 63 words in Lab_20.txt file
There are 7 lines in Lab_20.txt file
TASK 20.2: Count the Word [2 points]
Write a program that asks user to enter the text file name and the word
to count and display the count equal to number of times it appeared in
given text file.
Enter the file name >> Lab_20.txt
Sample Output Enter the word >> fox
The word "fox" appeared 7 times in Lab_20.txt file
TASK 20.3: Biodata [2 points]

8|Page Computer Programming-I Lab


Department of Mechatronics and Control Engineering
University of Engineering and Technology Lahore

Write a function Biodata() that asks user to enter following information


and stores it in a text file named as the name of user:
• Name:
• Father Name:
• Address:
• Contact:
• Profession:
• Marital Status:
• Religion:
• Nationality:
• Hobbies:
Function Biodata() takes no parameters and return nothing. In main()
call the function 3 times to get and store the biodata of three persons.
Three text files (.txt) containing biodata of three
persons, e.g., file named (AhmadAli.txt) can contain
Name: Engr. Ahmad Ali
Father Name: M. Ali
Address: Model Town, Lahore
Expected Output Contact: +92-333-4321567
Profession: Design Engineer
Marital Status: Single
Religion: Islam
Nationality: Pakistani
Hobbies: Travel & Photography
TASK 20.4: Save Every Move [4 points]
Repeat the Task 16.4 Tic-Tac-Toe Game and save every move in a text file,
named as TTT_Game.txt, in the format as shown in sample output and the
status of game. User can play any number of games by running the program
again and again.
Game Number: 005
Game Status: Player-1 won the game!
| | | | | |o| | | |o| | | |o|o| |x|o|o| |x|o|o| |x|o|o|
Sample
------- ------- ------- ------- ------- ------- -------
Output
| |X| | | |x| | | |x| | | |x| | | |x| | |o|x| | |o|x| |
------- ------- ------- ------- ------- ------- -------
| | | | | | | | |x| | | |x| | | |x| | | |x| | | |x| |x|

9|Page Computer Programming-I Lab

You might also like