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

Module14-CC102

Uploaded by

darwinteberio0
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

Module14-CC102

Uploaded by

darwinteberio0
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 12

SELF-PACED LEARNING

MODULE
College
INFORMATION SHEET FN-4.1.1
“Input / Output, File I/O and Header Files”
Input & Output
When we are saying Input that means to feed some data into program. This can be given in the
form of file or from command line. C programming language provides a set of built-in functions to read
given input and feed it to the program as per requirement.
When we are saying Output that means to display some data on screen, printer or in any file. C
programming language provides a set of built-in functions to output the data on the computer screen as
well as you can save that data in text or binary files.

The Standard Files


C programming language treats all the devices as files. So devices such as the display are addressed in
the same way as files and following three file are automatically opened when a program executes to
provide access to the keyboard and screen.

The file points are the means to access the file for reading and writing purpose. This section will explain
you how to read values from the screen and how to print the result on the screen.

The getchar() & 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 characters 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. Check the following example:

#include <stdio.h>
int main( )
{
int c;
printf( "Enter a value :");
c = getchar( );
printf( "\nYou entered: ");
putchar( c );
return 0;
}
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 only a single character and displays it as
follows:
$./a.out
Enter a value : this is test
You entered: t

The gets() & 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.
The int puts(const char *s) function writes the string s and a trailing newline to stdout.
#include <stdio.h>
int main( )
{
char str[100];
printf( "Enter a value :");
str = gets( str );
printf( "\nYou entered: ");
puts( str );
return 0;
}

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 complete line till end and displays it as
follows:
$./a.out
Enter a value : this is test
You entered: This is test

The scanf() and printf() functions


The int scanf(const char *format, ...) function reads input from the standard input stream stdin
and scans that input according to format provided.
The int printf(const char *format, ...) function writes output to the standard output stream
stdout and produces output according to a 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. For a complete detail you can refer to a man page for these
function. For now let us proceed with a simple example which makes things clear:
#include <stdio.h>
int main( )
{
char str[100];
int i;
printf( "Enter a value :");
scanf("%s %d", str, &i);
printf( "\nYou entered: %s, %d ", str, i);
return 0;
}

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 as follows:
$./a.out
Enter a value : seven 7
You entered: seven 7

Here, it should be noted that scanf() expect input in the same format as you provided %s and
%d, which means you have to provide valid input like "string integer", if you provide "string string" or
"integer integer" then it will be assumed as wrong input. Second, while reading a string scanf() stops
reading as soon as it encounters a space so "this is test" are three strings for scanf().

File I/O
Last chapter explained about standard input and output devices handled by C programming
language. This chapter we will see how C programmers can create, open, close text or binary files for
their data storage.
A file represents a sequence of bytes, does not matter if it is a text file or 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 chapter will take you through important calls for the 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.
Following is the prototype of this function call:
FILE *fopen( const char * filename, const char * mode );
Here, filename is string literal, which you will use to name your file and access mode can have one of the
following values:
If you are going to handle binary files then you will use below mentioned access modes instead of the
above mentioned:

Closing a File
To close a file, use the fclose( ) function. The prototype of this function is:
int fclose( FILE *fp );
The fclose( ) function returns zero on success, or EOF if there is an error in closing the file. This
function actually, 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 provide by C standard library to read and write a file character by
character or in the form of a fixed length string. Let us see few of the in the next section.

Writing a File
Following is the simplest function to write individual characters to a stream:
int fputc( int c, FILE *fp );
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:
int fputs( const char *s, FILE *fp );
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:

When the above code is compiled and executed, it creates a new file test.txt in /tmp directory and
writes two lines using two different functions. Let us read this file in next section.

Reading a File
Following 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 functions allow you to read a
string from a stream:
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 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 the first space character encounters.

When the above code is compiled and executed, it reads the file created in previous section
and produces the following result:
1 : This
2: is testing for fprintf...
3: This is testing for fputs...

Let's see a little more detail about what happened here. First fscanf() method read just This
because after that it encountered a space, second call is for fgets() which read the remaining line till it
encountered end of line. Finally last call fgets() read second line completely.
Binary I/O Functions
There are following two functions, which can be used for binary input and output:

Both of these functions should be used to read or write blocks of memories - usually arrays or
structures.

Header Files
A header file is a file with extension .h which contains C function declarations and macro
definitions and to be shared between several source files. There are two types of header files: the files
that the programmer writes and the files that come with your compiler.
You request the use of a header file in your program by including it, with the C preprocessing
directive #include like you have seen inclusion of stdio.h header file. which comes along with your
compiler.
Including a header file is equal to copying the content of the header file but we do not do it
because it will be very much error-prone and it is not a good idea to copy the content of header file in
the source files, specially if we have multiple source file comprising our program.
A simple practice in C or C++ programs is that we keep all the constants, macros, system wide
global variables, and function prototypes in header files and include that header file wherever it is
required.

Include Syntax
Both user and system header files are included using the preprocessing directive #include. It has
following two forms:
#include <file>
This form is used for system header files. It searches for a file named file in a standard list of system
directories. You can prepend directories to this list with the -I option while compiling your source code.
#include "file"
This form is used for header files of your own program. It searches for a file named file in the directory
containing the current file. You can prepend directories to this list with the -I option while compiling
your source code.

Include Operation
The #include directive works by directing the C preprocessor to scan the specified file as input before
continuing with the rest of the current source file. The output from the preprocessor contains the
output already generated, followed by the output resulting from the included file, followed by the
output that comes from the text after the #include directive. For example, if you have a header file
header.h as follows:
char *test (void);
and a main program called program.c that uses the header file, like this:
the compiler will see the same token stream as it would if program.c read

Once-Only Headers
If a header file happens to be included twice, the compiler will process its contents twice and will result
an error. The standard way to prevent this is to enclose the entire real contents of the file in a
conditional, like this:
#ifndef HEADER_FILE
#define HEADER_FILE
the entire header file file
#endif
This construct is commonly known as a wrapper #ifndef. When the header is included again, the
conditional will be false, because HEADER_FILE is defined. The preprocessor will skip over the entire
contents of the file, and the compiler will not see it twice.
Computed Includes
Sometimes it is necessary to select one of several different header files to be included into your
program. They might specify configuration parameters to be used on different sorts of operating
systems, for instance. You could do this with a series of conditionals as follows:

But as it grows, it becomes tedious, instead the preprocessor offers the ability to use a macro for the
header name. This is called a computed include. Instead of writing a header name as the direct
argument of #include, you simply put a macro name there instead:

SYSTEM_H will be expanded, and the preprocessor will look for system_1.h as if the #include had been
written that way originally. SYSTEM_H could be defined by your Makefile with a -D option
Reference: Workbook in C Programming Computer Programming 1 by Paulino H. Gatpandan, Azenith M. Rollan
https://www.unf.edu/~wkloster/2220/ppts/cprogramming..pdf
SELF CHECK FN-4.1.1
A. What is the final output of the following code?

Enter a value: You are my sunshine


SELF CHECK ANSWER KEY FN-4.1.1

A.
STUDENT NAME: __________________________________ SECTION: __________________

PERFORMANCE TASK FN-4.1.1


PERFORMANCE TASK TITLE: C Program (Games)

PERFORMANCE OBJECTIVE: The learners independently demonstrate core competencies about C


programs
MATERIALS:
Computer / Android phone
Applications / Software:
Computer: TurboC2
Android phone: Coding C
Procedure:
A. Search a simple C program (Games), run and test it.
B. Send the file or screenshot of code and output in Edmodo platform.

PRECAUTIONS:
 Undertake final inspections to ensure the program conform to requirements
ASSESSMENT METHOD: PERFORMANCE TASK CRITERIA CHECKLIST
STUDENT NAME: __________________________________ SECTION: __________________

PERFORMANCE TASK CRITERIA CHECK LIST FN-4.1-1


SCORING
CRITERIA
1 2 3 4 5
1. Quality of Work – the ability to follow procedures with precision and the
art, skill and finality of work
2. Speed – efficiency of work
3. Proper use of statement – the ability to apply proper statement for a
given task
TEACHER’S REMARKS:  QUIZ  RECITATION  PROJECT
GRADE:

5 - Excellently Performed
4 - Very Satisfactorily Performed
3 - Satisfactorily Performed
2 - Fairly Performed
1 - Poorly Performed

_________________________________
TEACHER

Date: ______________________

You might also like