0% found this document useful (0 votes)
10 views47 pages

CP unit-III

This document covers the preprocessor and file handling in C, detailing common preprocessor commands and various file operations including reading, writing, and appending data to text and binary files. It includes a series of short and long answer questions related to file types, operations, and preprocessor directives, along with examples of C programs demonstrating these concepts. Additionally, it explains the basic console I/O functions and formatted input/output functions like printf() and scanf().

Uploaded by

Aarthik Buguda
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)
10 views47 pages

CP unit-III

This document covers the preprocessor and file handling in C, detailing common preprocessor commands and various file operations including reading, writing, and appending data to text and binary files. It includes a series of short and long answer questions related to file types, operations, and preprocessor directives, along with examples of C programs demonstrating these concepts. Additionally, it explains the basic console I/O functions and formatted input/output functions like printf() and scanf().

Uploaded by

Aarthik Buguda
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/ 47

UNIT – III

Preprocessor and File handling in C: Preprocessor: Commonly used Preprocessor commands


like include, define, undef, if, ifdef, ifndef Files: Text and Binary files, Creating and Reading
and writing text and binary files, Appending data to existing files, Writing and reading
structures using binary files, Random access using fseek, ftell and rewind functions.

SHORT ANSWER QUESTIONS


1. What is a file? What are different types of files?
2. Explain the file operations in detail?
3. Differentiate unformatted data file and binary files?
4. List different random file accessing mechanisms?
5. What is the use of c pre processors?
6. Define macros?
7. What are the pre-processor directives?
8. Define fscanf() and fprint() functions.
9. Write a statement to open a file in reading mode
10. Write a sample C program to demonstrate the control string of
scanf() function.
11. Write a sample C program to demonstrate the control string of
scanf() function.
12. Discuss the types of streams.
13. Define a file?
14. What is the problem with getchar() ?
15. Define Stream. List types of streams.
16. List the basic console I/O functions.
17. Discuss pre-processor directives in C.
18. What is a pre-processor?
19. What role does the fseek() plays and how many arguments
does it have?

LONG ANSWER QUESTIONS


1. List different data input and output functions?
2. Explain file operations with example?
3. Write a program to representing fseek and ftell functions?
4. Explain the concept of binary file?
5. What is the difference between getchar and getc functions?
6. What is the difference between putchar and putc functions?

I B.Tech COMPUTER PROGRAMMING UNIT-III 1


7. Write the syntaxes for putc and puts functions?
8. Write in detail about data input functions with examples?
9. Write in detail about data output functions with examples?
10. Explain various file operation functions with examples.
11. Write a program for copy one file content to another file .
12. Give brief description about the various file status functions.
13. write a program to copy one file content to another file.
14. what is file stream? Explain file operations with examples?
15. write a program for read and write operation of binary files.
16. Write a C Program to Copy the contents of one file to another
17. What do you mean by C preprocessor. Give example of any
two preprocessor directive.

What are the Compiler preprocessor directives statements ?List and


define the preprocessor statements in C?

You can include various instructions to the compiler in the source


code of a C program. These are called preprocessor directives, and
they expand the scope of the programming environment. This
chapter also examines comments.
The Preprocessor
As you can see, all preprocessor directives begin with a # sign. In
addition, each preprocessing directive must be on its own line. For
example, this will not work:
#include <stdio.h> #include <stdlib.h>
The preprocessor directives are shown here:

1.#define
2.#endif
3. #ifdef
4.#line
5.#elif
6. #error
7. #ifndef
8. #pragma
9.#else
10.#if

I B.Tech COMPUTER PROGRAMMING UNIT-III 2


11. #include
12.#undef

1. #define
The #define directive defines an identifier and a character sequence (a
set of characters) that will be substituted for the identifier each time it
is encountered in the source file. The identifier is referred to as a
macro name and the replacement process as macro replacement. The
general form of the directive is
#define macro-name char-sequence
For example, if you wish to use the word LEFT for the value 1 and
the word RIGHT for the value 0, you could declare these two #define
directives:
#define LEFT 1
#define RIGHT 0
This causes the compiler to substitute a 1 or a 0 each time LEFT or
RIGHT is encountered in your source file. For example, the following
prints 0 1 2 on the screen:
printf("%d %d %d", RIGHT, LEFT, LEFT+1);
Defining Function-like Macros
The #define directive has another powerful feature: The macro name
can have arguments. Each time the macro name is encountered, the
arguments used in its definition are replaced by the actual
arguments found in the program. This form of a macro is called a
function-like macro. For example:

#include <stdio.h>
#define ABS(a) (a) < 0 ? -(a) : (a)
int main(void)
{
printf("abs of -1 and 1: %d %d", ABS(-1), ABS(1));
return 0;
}

2. #error
The #error directive forces the compiler to stop compilation. It is used
primarily for debugging. The general form of the #error directive is

I B.Tech COMPUTER PROGRAMMING UNIT-III 3


#error error-message
The error-message is not between double quotes. When the #error
directive is encountered, the error message is displayed, possibly
along with other information defined by the compiler

3. #include
The #include directive tells the compiler to read another source file in
addition to the one that contains the #include directive. The name of
the source file must be enclosed between double quotes or angle
brackets. For example,
#include "stdio.h"
#include <stdio.h>
both cause the compiler to read and compile the header for the I/O
system library functions.
Include files can have #include directives in them.

4. Conditional Compilation Directives #if, #else, #elif, and #endif::


Perhaps the most commonly used conditional compilation directives
are #if, #else, #elif, and #endif.
These directives allow you to conditionally include portions of code
based upon the outcome of a constant expression.
The general form of #if is
#if constant-expression
statement sequence
#endif
If the constant expression following #if is true, the code that is
between it and #endif is compiled.
Otherwise, the intervening code is skipped. The #endif directive
marks the end of an #if block. For Example 1::
/* Simple #if example. */
#include <stdio.h>
#define MAX 100
int main(void)
{
#if MAX>99
printf(''Compiled for array greater than 99.\n");
#endif

I B.Tech COMPUTER PROGRAMMING UNIT-III 4


return 0;
}
Example 2::
/* Simple #if/#else example. */
#include <stdio.h>
#define MAX 10
int main(void)
{
#if MAX>99
printf("Compiled for array greater than 99.\n");
#else
printf("Compiled for small array.\n");
#endif
return 0;
}
The #elif directive means "else if" and establishes an if-else-if chain
for multiple compilation options. #elif is followed by a constant
expression. If the expression is true, that block of code is compiled
and no other #elif expressions are tested. Otherwise, the next block in
the series is checked. The general form for #elif is
#if expression
statement sequence
#elif expression 1
statement sequence
#elif expression 2
statement sequence
#elif expression 3
statement sequence
#elif expression 4
...
#elif expression N
statement sequence
#endif
For example, the following fragment uses the value of
ACTIVE_COUNTRY to define the currency sign:

5.#ifdef and #ifndef

I B.Tech COMPUTER PROGRAMMING UNIT-III 5


Another method of conditional compilation uses the directives #ifdef
and #ifndef, which mean ''if defined" and "if not defined,"
respectively. The general form of #ifdef is
#ifdef macro-name
statement sequence
#endif
If macro-name has been previously defined in a #define statement, the
block of code will be
compiled.
The general form of #ifndef is
#ifndef macro-name
statement sequence
#endif
If macro-name is currently undefined by a #define statement, the
block of code is compiled.
Both #ifdef and #ifndef may use an #else or #elif statement.
For example,
#include <stdio.h>
#define TED 10
int main(void)
{
#ifdef TED
printf("Hi Ted\n");
#else
printf("Hi anyone\n");
#endif
#ifndef RALPH
printf("RALPH not defined\n");
#endif
return 0;
}

6. #undef

I B.Tech COMPUTER PROGRAMMING UNIT-III 6


The #undef directive removes a previously defined definition of the
macro name that follows it—that is, it ''undefines" a macro. The
general form for #undef is
#undef macro-name
For example:
#define LEN 100
#define WIDTH 100
char array[LEN][WIDTH];
#undef LEN
#undef WIDTH
/* at this point both LEN and WIDTH are undefined */

7. #line
The #line directive changes the contents of _ _LINE_ _ and _ _FILE
_, which are predefined
identifiers in the compiler. The _ _LINE_ _ identifier contains the line
number of the currently compiled line of code. The _ _FILE_ _
identifier is a string that contains the name of the source file
being compiled. The general form for #line is
#line number "filename"
where number is any positive integer and becomes the new value of _
_LINE_ _, and the optional
filename is any valid file identifier, which becomes the new value of _
FILE_ _. #line is primarily
used for debugging and special applications.

#include <stdio.h>
#line 100 /* reset the line counter */
int main(void) /* line 100 */
{ /* line 101 */
printf("%d\n", _ _LINE_ _); /* line 102 */
return 0;
}
8. #pragma
#pragma is an implementation-defined directive that allows various
instructions to be given to the

I B.Tech COMPUTER PROGRAMMING UNIT-III 7


compiler. For example, a compiler may have an option that supports
program execution tracing. A trace option would then be specified by
a #pragma statement. You must check the compiler's documentation
for details and options.
9. The # and ## Preprocessor Operators
There are two preprocessor operators: # and ##. These operators are
used with the #define statement.
The # operator, which is generally called the stringize operator, turns
the argument it precedes into a quoted string. For example, consider
this program:
#include <stdio.h>
#define mkstr(s) # s
int main(void)
{
printf(mkstr(I like C));
return 0;
}
The preprocessor turns the line
printf(mkstr(I like C));
into
printf("I I like C”)

I B.Tech COMPUTER PROGRAMMING UNIT-III 8


Basic console I/O functions

Function Operation

getchar( ) Reads a character from the keyboard; usually waits


for carriage return.
getche( ) Reads a character with echo; does not wait for
carriage return; not defined by Standard C, but a
common extension.
getch( ) Reads a character without echo; does not wait for
carriage return; not defined by Standard C, but a
common extension.
putchar( ) Writes a character to the screen.
gets( ) Reads a string from the keyboard.
puts( ) Writes a string to the screen.

Reading and Writing Characters


The simplest of the console I/O functions are getchar( ) , which reads
a character from the keyboard,and putchar( ), which writes a character
to the screen. The getchar( ) function waits until a key is pressed and
then returns its value. The keypress is also automatically echoed to the
screen. The putchar( ) function writes a character to the screen at the
current cursor position. The prototypes for getchar( ) and putchar( )
are shown here:

int getchar(void);
int putchar(int c);
As its prototype shows, the getchar( ) function is declared as returning
an integer. However, you can assign this value to a char variable, as is
usually done, because the character is contained in the low-order byte.
(The high-order byte is usually zero.) getchar( ) returns EOF if an
error occurs. (The EOF macro is defined in <stdio.h> and is often
equal to –1.)

In the case of putchar( ), even though it is declared as taking an


integer parameter, you will generally call it using a character
argument. Only the low-order byte of its parameter is actually output

I B.Tech COMPUTER PROGRAMMING UNIT-III 9


to the screen. The putchar( ) function returns the character written or
EOF if an error occurs.

#include <stdio.h>
#include <ctype.h>
main()
{
char ch;
printf("Enter some text (type a period to quit).\n");
do
{
ch = getchar();
if(islower(ch))
ch = toupper(ch);
else
ch = tolower(ch);
putchar(ch);
} while (ch != '.');
Getch();
}
Explanation
The above program illustrates getchar( ) and putchar( ). It inputs
characters from the keyboard and displays them in reverse case. That
is, it prints uppercase as lowercase and lowercase as uppercase. To
stop the program, enter a period.

A Problem with getchar( )

There are some potential problems with getchar( ). For many


compilers, getchar( ) is implemented in such a way that it buffers
input until ENTER is pressed. This is called line-buffered input; you
have to press ENTER before any character is returned. Also, since
getchar( ) inputs only one character each time it is called, line
buffering may leave one or more characters waiting in the input
queue, which is annoying in interactive environments. Even though it
is permissible for getchar( ) to be implemented as an

I B.Tech COMPUTER PROGRAMMING UNIT-III 10


Two of the most common alternative functions:: getch( ) and getche(
), have these prototypes:
int getch(void);
int getche(void);

For example, the previous program is shown here using getch( )


instead of getchar( ) :
#include <stdio.h>
#include <conio.h>
#include <ctype.h>
int main(void)
{
char ch;
printf("Enter some text (type a period to quit).\n");
do {
ch = getch();
if(islower(ch))
ch = toupper(ch);
else
ch = tolower(ch);
putchar(ch);
} while (ch != '.');
getch()
}

Reading and Writing Strings


The next step up in console I/O, in terms of complexity and power,
are the functions gets( ) and puts( ). They enable you to read and write
strings of characters.

gets()::
The gets( ) function reads a string of characters entered at the
keyboard and stores them at the address pointed to by its argument.
You can type characters at the keyboard until you strike a carriage
return. The carriage return does not become part of the string; instead,
a null terminator is placed at the end, and gets( ) returns. In fact, you
cannot use gets( ) to return a carriage return (although getchar( ) can

I B.Tech COMPUTER PROGRAMMING UNIT-III 11


do so). You can correct typing mistakes by using the backspace key
before pressing ENTER. The prototype for gets( ) is
char *gets(char *str);

puts()::
The puts( ) function writes its string argument to the screen
followed by a newline. Its prototype is
int puts(const char *str);
puts( ) recognizes the same backslash escape sequences as printf( ),
such as \t for tab. A call to puts ( ) requires far less overhead than the
same call to printf( ) because puts( ) can only output a string of
characters— it cannot output numbers or do format conversions.
Therefore, puts( ) takes up less space and runs faster than printf( ). For
this reason, the puts( ) function is often used when no format
conversions are required.

Formatted Console I/O


The functions printf( ) and scanf( ) perform formatted output and
input— that is, they can read and write data in various formats that are
under your control. The printf( ) function writes data to the console.
The scanf( ) function, its complement, reads data from the keyboard.
Both functions can operate on any of the built-in data types, plus null-
terminated character strings.

printf( )
The prototype for printf( ) is
int printf(const char *control_string, . . . );
The printf( ) function returns the number of characters written or a
negative value if an error occurs.
The control_string consists of two types of items. The first type is
composed of characters that will be printed on the screen. The second
type contains format specifiers that define the way the subsequent
arguments are displayed.
For example
printf("I like %c %s", 'C', "very much!");
displays
I like C very much!

I B.Tech COMPUTER PROGRAMMING UNIT-III 12


Here, the %c matches the character 'C', and the %s matches the string
"very much".
printf( ) Format Specifiers

Code Format
%a Hexadecimal output in the form 0xh.hhhhp+d (C99
only).
%A Hexadecimal output in the form 0Xh.hhhhP+d (C99
only).
%c Character.
%d Signed decimal integers.
%i Signed decimal integers.
%e Scientific notation (lowercase e).
%E Scientific notation (uppercase E).
%f Decimal floating point.
%g Uses %e or %f, whichever is shorter.
%G Uses %E or %F, whichever is shorter.
%o Unsigned octal.
%s String of characters.
%u Unsigned decimal integers.
%x Unsigned hexadecimal (lowercase letters).
%X Unsigned hexadecimal (uppercase letters).
%p Displays a pointer.
%n The associated argument must be a pointer to an integer. This
specifier causes the number of characters written (up to the point at
which the %n is encountered) to be stored in that integer.

%% Prints a % sign.

1) To print an individual character, use %c. To print a string, use %s.

2) You can use either %d or %i to display a signed integer in decimal


format. These format specifiers
are equivalent; To output an unsigned integer, use %u.

I B.Tech COMPUTER PROGRAMMING UNIT-III 13


3) The %f format specifier displays numbers in floating point. The %e
and %E specifiers tell printf( ) to display a double argument in
scientific notation.

4) You can tell printf( ) to use either %f or %e by using the %g or %G


format specifiers. This causes
printf( ) to select the format specifier that produces the shortest
output. Where applicable, use %G
if you want E shown in uppercase; otherwise, use %g. The following
program demonstrates the
effect of the %g format specifier:

#include <stdio.h>
int main(void)
{
double f;
for(f=1.0; f<1.0e+10; f=f*10)
printf(''%g ", f);
return 0;
}

It produces the following output:


1 10 100 1000 10000 100000 1e+006 1e+007 1e+008 1e+009

5) You can display unsigned integers in octal or hexadecimal format


using %o and %x, respectively.
Since the hexadecimal number system uses the letters A through F to
represent the numbers 10
through 15, you can display these letters in either upper- or lowercase.
For uppercase, use the %X
format specifier; for lowercase, use %x, as shown here:

#include <stdio.h>
int main(void)
{
unsigned num;
for(num=0; num < 16; num++)

I B.Tech COMPUTER PROGRAMMING UNIT-III 14


{
printf(''%o ", num);
printf("%x ", num);
printf("%X\n", num);
}
return 0;
}

The output is shown here:

000
111
222
333
444
555
666
777
10 8 8
11 9 9
12 a A
13 b B
14 c C
15 d D
16 e E
17 f F

6) If you want to display an address, use %p. This format specifier


causes printf( ) to display a
machine address in a format compatible with the type of addressing
used by the computer. The next
program displays the address of sample:
#include <stdio.h>
int sample;
int main(void)
{
printf(''%p", &sample);

I B.Tech COMPUTER PROGRAMMING UNIT-III 15


return 0;
}
7) The %n Specifier
The %n format specifier is different from the others. Instead of telling
printf( ) to display something, it causes printf( ) to load the integer
variable pointed to by its corresponding argument with a value equal
to the number of characters that have been output. In other words, the
value that corresponds to the %n format specifier must be a pointer to
a variable. After the call to printf( ) has returned, this variable will
hold the number of characters output, up to the point at which the %n
was encountered. Examine the next program to understand this
somewhat unusual format code:

#include <stdio.h>
int main(void)
{
int count;
printf("this%n is a test\n", &count);
printf("%d", count);
return 0;
}
This program displays this is a test followed by the number 4. The %n
format specifier is used
primarily to enable your program to perform dynamic formatting.
8) The Minimum Field Width Specifier
An integer placed between the % sign and the format code acts as a
minimum field width specifier. For example, %05d will pad a number
of less than five digits with 0's so that its total length is five. The
following program demonstrates the minimum field width specifier:

#include <stdio.h>
int main (void)
{
double item;
item = 10.12304;
printf("%f\n", item);
printf(''%10f\n", item);

I B.Tech COMPUTER PROGRAMMING UNIT-III 16


printf("%012f\n", item);
return 0;
}

This program produces the following output:


10.123040
10.123040
00010.123040

9 The Precision Specifier


When you apply the precision specifier to floating-point data using
the %f, %e, or %E specifiers, it
determines the number of decimal places displayed. For example,
%10.4f displays a number at least
10 characters wide with four decimal places.
When the precision specifier is applied to %g or %G, it specifies the
number of significant digits.
Applied to strings, the precision specifier specifies the maximum field
length. For example, %5.7s
displays a string at least five and not exceeding seven characters long.
The following program illustrates the precision specifier:
#include <stdio.h>
int main(void)
{ printf("%.4f\n", 123.1234567);
printf(''%3.8d\n", 1000);
printf("%10.15s\n", "This is a simple test.");
return 0;
}
It produces the following output:
123.1235
00001000
This is a simpl
10) Justifying Output
By default, all output is right justified. That is, if the field width is
larger than the data printed, the
data will be placed on the right edge of the field. You can force output
to be left justified by placing

I B.Tech COMPUTER PROGRAMMING UNIT-III 17


a minus sign directly after the %. For example, %–10.2f left-justifies a
floating-point number with
two decimal places in a 10-character field.
The following program illustrates left justification:
#include <stdio.h>
int main(void)
{printf(".........................\n");
printf("right-justified: %8d\n", 100);
printf(" left-justified: %-8d\n", 100);
return 0;
}
The output is shown here:
right-justified: 100
left-justified: 100

scanf( )
scanf( ) is the general -purpose console input routine. It can read all
the built-in data types and automatically convert numbers into the
proper internal format. It is much like the reverse of
printf( ). The prototype for scanf( ) is

int scanf(const char *control_string, . . . );

The scanf( ) function returns the number of data items successfully


assigned a value. If an error occurs, scanf( ) returns EOF. The
control_string determines how values are read into the variables
pointed to in the argument list.
The control string consists of three classifications of characters:
• Format specifiers
• White-space characters
• Non-white-space characters
Let's take a look at each of these now.
Format Specifiers
The input format specifiers are preceded by a % sign and tell scanf( )
what type of data is to be read
next. These codes are listed in Table 8-3. The format specifiers are
matched, in order from left to

I B.Tech COMPUTER PROGRAMMING UNIT-III 18


right, with the arguments in the argument list. Let's look at some
examples.
Inputting Numbers
To read an integer, use either the %d or %i specifier. To read a
floating-point number represented
in either standard or scientific notation, use %e, %f, or %g. (C99 also
includes %a, which reads a
floating-point number.)
You can use scanf( ) to read integers in either octal or hexadecimal
form by using the %o and %x
format commands, respectively. The %x can be in either upper- or
lowercase. Either way, you can
enter the letters A through F in either case

scanf( ) Format Specifiers

Code Meaning
%a Reads a floating -point value (C99 only).
%c Reads a single character.
%d Reads a decimal integer.
%i Reads an integer in either decimal, octal, or hexadecimal
format.
%e Reads a floating -point number.
%f Reads a floating -point number.
%g Reads a floating -point number.
%o Reads an octal number.
%s Reads a string.
%x Reads a hexadecimal number.
%p Reads a pointer.
%n Receives an integer value equal to the number of
characters read so far.
%u Reads an unsigned decimal integer.
%[ ] Scans for a set of characters.
%% Reads a percent sign.

The following program reads an octal and hexadecimal


number:

I B.Tech COMPUTER PROGRAMMING UNIT-III 19


#include <stdio.h>
int main(void)
{
int i, j;
scanf("%o%x", &i, &j);
printf(''%o %x", i, j);
return 0;
}

1) Inputting Unsigned Integers


To input an unsigned integer, use the %u format specifier. For
example,
unsigned num;
scanf(''%u", &num);
reads an unsigned number and puts its value into num.

2) Reading Individual Characters Using scanf( )


scanf("%c%c%c", &a, &b, &c);
returns with the character x in a, a space in b, and the character y in c.
3) Reading Strings
To see the effect of the %s specifier, try this program using the string
"hello there":
#include <stdio.h>
int main(void)
{
char str[80];
printf("Enter a string: ");
scanf(''%s", str);
printf("Here's your string: %s", str);
return 0;
}
4. The %n Specifier
The %n specifier instructs scanf( ) to store the number of characters
read from the input stream (up to the point at which the %n was
encountered) in the integer variable pointed to by the corresponding
argument.

I B.Tech COMPUTER PROGRAMMING UNIT-III 20


Standard C Vs UNIX File I/O – Streams and Files

C vs. C++ File I/O


Because C forms the foundation for C++, there is sometimes
confusion over how C's file system relates to C++. First, C++
supports the entire C file system. Thus, if you will be porting older C
code to C++, you will not have to change all of your I/O routines right
away. Second, C++ defines its own, object-oriented I/O system,
which includes both I/O functions and I/O operators. The C++ I/O
system completely duplicates the functionality of the C I/O system
and renders the C file system redundant. In general, if you are writing
C++ programs, you will usually want to use the C++ I/O system, but
you are free to use the C file system if you like.

INTRODUCTION
Input means transferring data from input device to program. Output
means transferring data from program to output device. Here data
transfer is also called stream. Stream means a sequence of bits or
bytes.
By default, program I/O done through standard input and standard
output. Generally standard input device is keyboard and standard
output device is monitor(or screen). That is, by default program
connected to keyboard for input and program connected to monitor
for output.
File concept changes the standard input and standard output. That is,
program I/O done through the files. For program input, standard input
device keyboard is replaced with file and for program output standard
output device is replaced with the file. So, files allow a programmer
to do I/O with files.
Program that deals data with standard input and output devices is
temporary. That is, when the program ends , we loose data. So, to deal
with permanent data we use files.
Program that deals data with standard i/o devices is limited. That is,
not possible to transfer huge amount of data, that is possible only
through files.

Standard C vs. Unix File I/O

I B.Tech COMPUTER PROGRAMMING UNIT-III 21


C was originally implemented for the Unix operating system. As
such, early versions of C (and many still today) support a set of I/O
functions that are compatible with Unix. This set of I/O functions is
sometimes referred to as the Unix-like I/O system, or the unbuffered
I/O system. However, when C was standardized, the Unix-like
functions were not incorporated into the standard, largely because
they are redundant. Also, the Unix-like system may not be relevant to
certain environments that could otherwise support C. In the time that
has elapsed since the previous edition, use of the standard I/O
functions has steadily risen and use of the Unix-like functions has
steadily decreased. Today, most programmers use the standard
functions because they are portable to all environments (and to C++).
Programmers wanting to use the Unix like functions should consult
their compiler's documentation.
Streams and Files
Before beginning our discussion of the C file system it is necessary to
know the difference between the terms streams and files. The C I/O
system supplies a consistent interface to the programmer independent
of the actual device being accessed. That is, the C I/O system provides
a level of abstraction between the programmer and the device. This
abstraction is called a stream, and the actual device is called a file. It
is important to understand how streams and files interact.
Streams
The C file system is designed to work with a wide variety of devices,
including terminals, disk drives, and tape drives. Even though each
device is very different, the buffered file system transforms each into
a logical device called a stream. All streams behave similarly.
Because streams are largely device independent, the same function
that can write to a disk file can also write to another type of device,
such as the console. There are two types of streams: text and binary.
Text Streams
A text stream is a sequence of characters. Standard C states that a text
stream is organized into lines
terminated by a newline character. However, the newline character is
optional on the last line. In a text stream, certain character translations
may occur as required by the host environment. For example, a
newline may be converted to a carriage return/linefeed pair.

I B.Tech COMPUTER PROGRAMMING UNIT-III 22


Therefore, there may not be a one-to-one relationship between the
characters that are written (or read) and those stored on the external
device. Also, because of possible translations, the number of
characters written (or read) may not be the same as the number that is
stored on the external device.
Binary Streams
A binary stream is a sequence of bytes that has a one-to-one
correspondence to the bytes in the external device— that is, no
character translations occur. Also, the number of bytes written (or
read) is the same as the number on the external device. However, an
implementation— defined number of null bytes may be appended to a
binary stream. These null bytes might be used to pad the information
so that it fills a sector on a disk, for example.

Files
The file is a permanent storage medium in which we can store the
data permanently.
Or
A file represents a sequence of bytes on the disk where a group of
related data is stored. File is created for permanent storage of data.
Or
A File is a collection of data stored on a secondary storage device like
hard disk. File operation is to combine all the input data into a file and
then to operate through the C program. Various operations like
insertion, deletion, opening closing etc can be done upon a file. When
the program is terminated, the entire data is lost in C programming. If
you want to keep large volume of data, it is time consuming to enter
the entire data. But, if file is created these information can be accessed
using few commands.

In C, a file may be anything from a disk file to a terminal or printer.


You associate a stream with a specific file by performing an open
operation. Once a file is open, information can be exchanged between
it and your program. Not all files have the same capabilities. For
example, a disk file can support random access, while some printers
cannot. This brings up an important point about the C I/O system: All
streams are the same, but all files are not. If the file can support

I B.Tech COMPUTER PROGRAMMING UNIT-III 23


position requests, opening that file also initializes the file position
indicator to the start of the file. As each character is read from or
written to the file, the position indicator is incremented, ensuring
progression through the file. You disassociate a file from a specific
stream with a close operation. If you close a file opened for output,
the contents, if any, of its associated stream are written to the external
device. This process, generally referred to as flushing the stream,
guarantees that no information is accidentally left in the disk buffer.
All files are closed automatically when your program terminates
normally, either by main( ) returning to the operating system or by a
call to exit( ). Files are not closed when a program terminates
abnormally, such as when it crashes or when it calls abort( ). Each
stream that is associated with a file has a file control structure of type
FILE. Never modify this file control block.

Declaring a File
The data structure FILE, which is defined in stdio.h used to declare a
file.File control structure for streams.

typedef struct {
short level;
unsigned flags;
char fd;
unsigned char hold;
short bsize;
unsigned char *buffer, *curp;
unsigned istemp;
short token;
} FILE;

The following syntax used to declare a file pointer:

FILE *file_pointer;

I B.Tech COMPUTER PROGRAMMING UNIT-III 24


The file_pointer is used to connect with files , which are actually
residing in secondary storage device.

Definition of File::
A file is a collection of related information. Actually files are residing
in secondary storage devices such as hard disk , floppy disk etc. (OR)
File is a set of record that can be accessed through the set of library
functions.

Commonly Used C File-System Functions:


Name Function
fopen( ) Opens a file
fclose( ) Closes a file
putc( ) Writes a character to a file
fputc( ) Same as putc( )
getc( ) Reads a character from a file
fgetc( ) Same as getc( )
fgets( ) Reads a string from a file
fputs( ) Writes a string to a file
fseek( ) Seeks to a specified byte in a file
ftell( ) Returns the current file position
fprintf( ) Is to a file what printf( ) is to the console
fscanf( ) Is to a file what scanf( ) is to the console
feof( ) Returns true if end-of-file is reached
ferror( ) Returns true if an error has occurred
rewind( ) Resets the file position indicator to the beginning of
the file
remove( ) Erases a file
fflush( ) Flushes a file

1.Explain different File Operations C language?


There are some of the file operations in c.
1. Opening a File:
The fopen( ) function opens a stream for use and links a file with that
stream. Then it returns the file
pointer associated with that file. Most often (and for the rest of this
discussion), the file is a disk file.

I B.Tech COMPUTER PROGRAMMING UNIT-III 25


The fopen( ) function has this prototype,

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

here fp indicates file pointer. A file pointer is a pointer to a structure


of type FILE. It points to information that defines various things
about the file, including its name, status, and the current position of
the file.
where filename is a pointer to a string of characters that make up a
valid filename and may include a path specification.
The string pointed to by mode determines how the file will be
opened.The following are the Legal Values for Mode
Mode Meaning
r Open a text file for reading
w Create a text file for writing
a Append to a text file
rb Open a binary file for reading
wb Create a binary file for writing
ab Append to a binary file
r+ Open a text file for read/write
w+ Create a text file for read/write
a+ Append or create a text file for read/write
r+b Open a binary file for read/write
w+b Create a binary file for read/write
a+b Append or create a binary file for read/write

The difference between modes r+ and w+ is that r+ will not create a


file if it does not exist; however, w+ will. Further, if the file already
exists, opening it with w+ destroys its contents; opening it with r+
does not.

For example , the following statements opens a file named “temp.txt”


in read mode.

FILE *fp;
fp = fopen(“temp.txt”,”r”); (OR) fp = fopen(“temp.txt”,”w”);

I B.Tech COMPUTER PROGRAMMING UNIT-III 26


The following illustrates the connection establishment between
program and secondary storage device with file name “temp.txt’. The
file pointer fp points to the file “temp.txt”, which is actually residing
in secondary storage device such as floppy disk, hard disk etc.

Example:
The following code uses fopen( ) to open a file named TEST for
output.
#include <stdio.h>
main()
{
FILE *fp;
fp = fopen("test.txt", "w");
if(fp==NULL)
{
printf(''Cannot open file.\n");
exit(1);
}
-----------
-----------
-----------
-----------
fclose(fp);
getch()
}

2. Closing a File

I B.Tech COMPUTER PROGRAMMING UNIT-III 27


The fclose( ) function closes a stream that was opened by a call to
fopen( ). It writes any data still
remaining in the disk buffer to the file and does a formal operating-
system-level close on the file.
The fclose( ) function has this prototype,
int fclose(FILE *fp);
where fp is the file pointer returned by the call to fopen( ).
Using fcloseall() function, closes all opened files, the following is the
declaration of fcloseall() function:

int fcloseall(void);

This function returns the total number of streams it closed. On error,


returns EOF
For example,

FILE *fread, *fwrite;


fread = fopen(“temp.txt”,”r”);
fwrite = fopen(“test.txt”,”w”);
……
……

fcloseall()

3. Writing a Character
The C I/O system defines two equivalent functions that output a
character: putc( ) and fputc( ). The putc( ) function writes characters
to a file that was previously opened for writing using the fopen( )
function. The prototype of this function is
int putc(int ch, FILE *fp);
fputc() finction returns a character c on success and returns EOF on
failure.
For example, consider the following statements:

char ch;
FILE *fwrite;
fwrite = fopen(“temp.txt”,”w”);

I B.Tech COMPUTER PROGRAMMING UNIT-III 28


Let us consider, the file “temp.txt” opened in write mode with the
contents specified in the below figure. Whenever the file opened , the
file pointer pointing to the file beginning position:

The following statement writes a character into the current position


and the pointer moved to next position to write next character:

ch=’A’;
fputc(ch,fwrite);

The following diagram illustrates this operation:

Write one more character into the file “temp.txt” using the following
statements:

ch=’B’;
fputc(ch,fwrite);

The following diagram illustrates this operation:

I B.Tech COMPUTER PROGRAMMING UNIT-III 29


The following program writes all alphabets A to Z into the file
“alpha.txt”:

#include<stdio.h>
int main()
{
char ch;
int i;
FILE *fwrite;
fwrite = fopen("temp.txt","w");
ch = 'A';
for(i=1;i<=26;i++)
{
fputc(ch,fwrite);
ch = ch + 1;
}
fclose(fwrite);
return 0;
}
After executing the above program “alpha.txt” looking like the
following:

4. Reading a Character
There are also two equivalent functions that input a character: getc( )
and fgetc( ). Both are defined
to preserve compatibility with older versions of C. The getc( )
function reads characters from a file opened in read mode by fopen( ).
The prototype of getc( ) is
int getc(FILE *fp);
where fp is a file pointer of type FILE returned by fopen( ).
For example, consider the following statements:

char ch;
FILE *fp;

I B.Tech COMPUTER PROGRAMMING UNIT-III 30


fp = fopen(“temp.txt”,”r”);

Let us consider, the file “temp.txt” opened in read mode with the
contents specified in the below figure. Whenever the file opened , the
file pointer pointing to the first character in the file:

Now we read a character from the file using the following statement:

ch = fgetc(fp);

The above statement read a character ‘g’ from the file and
immediately forwards the file pointer to the next character and the
read character stored in variable ‘ch’. After reading a character from
the file with file pointer shown below:

The file pointer automatically moved the next character after reading
a character.
Read next character,
ch = fgetc(fp);
After reading a character from the file with file pointer shown below:

The following code displays all contents from the file “temp.txt”:

I B.Tech COMPUTER PROGRAMMING UNIT-III 31


int main()
{
char ch;
FILE *fp;
fp = fopen(“temp.txt”,”r”);
while(1)
{
ch = fgetc(fp); /* Reads a character from the file */
if(ch==EOF) break;/* End of File */
printf(“%c”,ch);
}
fclose(fp);
}

5. Using feof( )
C includes the function feof( ), which determines when the end of the
file has been encountered. The feof( ) function has this prototype:
int feof(FILE *fp);
feof( ) returns true if the end of the file has been reached; otherwise, it
returns zero. Therefore, the following routine reads a binary file until
the end of the file is encountered:

6. Working with Strings : fputs( ) and fgets( )


File Input means opening the file in read mode, i.e. used to read the
contents from the file. To read the contents from the file first we need
to open the file in read mode.

In addition to getc( ) and putc( ), C supports the related functions


fgets( ) and fputs( ), which read and write character strings from and
to a disk file. These functions work just like putc( ) and getc( ), but
instead of reading or writing a single character, they read or write
strings. They have the following prototypes:
int fputs(const char *str, FILE *fp);
char *fgets(char *str, int length, FILE *fp);
The fputs( ) function writes the string pointed to by str to the specified
stream. It returns EOF if an

I B.Tech COMPUTER PROGRAMMING UNIT-III 32


error occurs.
The fgets( ) function reads a string from the specified stream until
either a newline character is read
or length–1 characters have been read.

7. rewind( )
The rewind( ) function resets the file position indicator to the
beginning of the file specified as its
argument. That is, it "rewinds" the file. Its prototype is
void rewind(FILE *fp);
where fp is a valid file pointer.
The rewind() function repositions file pointer to the beginning of the
file. The following is the declaration of rewind() function:

rewind(stream) is equivalent to fseek(stream, 0, SEEK_SET).

The following statements illustrate the rewind() function:


FILE *fp;
long pos;
fp = fopen(“TEST.TXT”,”w+”);
fprinf(fp,”One Two Three Four”);
fseek(fp, -3 ,SEEK_END);
After executing the above statement, the situation is looking like the
following:

rewind(fp);
After executing the above statement, the situation is looking like the
following:

printf(“\n Character at current position = %c”,fgetc(fp));


The above statement displays , Character at current position = O.

I B.Tech COMPUTER PROGRAMMING UNIT-III 33


8. ferror( )
The ferror( ) function determines whether a file operation has
produced an error. The ferror( )
function has this prototype,
int ferror(FILE *fp);
The following is the example program that illustrates this function:

int main()
{
FILE *fp;
fp = fopen("emp.dat", "w");
getc(fp);
if (ferror(fp) != 0)
{
printf("\nError reading from emp.dat");

}
}

9.Erasing Files

The remove( ) function erases the specified file. Its prototype is


int remove(const char *filename);
It returns zero if successful. Otherwise, it returns a nonzero value.

10. Flushing a Stream


If you wish to flush the contents of an output stream, use the fflush( )
function, whose prototype is
shown here:
int fflush(FILE *fp);
This function writes the contents of any buffered data to the file
associated with fp. If you call fflush
( ) with fp being null, all files opened for output are flushed. The
fflush( ) function returns zero if successful; otherwise, it returns EOF.

11.The clearerr() function

I B.Tech COMPUTER PROGRAMMING UNIT-III 34


This function resets error. That is, clearerr resets the file pointer error
and end-of-file indicators to 0. The following is the declaration of
clearer() function:

void clearer(FILE *stream);

The following is the example program that illustrates this function:

int main()
{
FILE *fp;
fp = fopen("emp.dat", "w");
getc(fp);
if (ferror(fp) != 0)
{
printf("\nError reading from emp.dat");
clearerr(fp);
}
}

12.The fgetpos() and fsetpos() functions


The fgetpos() function gets the current file pointer position. The
following is the declaration of fgetpos() function:

int fgetpos(FILE *stream, fpos_t *pos);

This function stores the position of the file pointer associated with the
given stream in the location *pos.

The fsetpos() function sets the file pointer position. The following is
the declaration of fgetpos() function:

int fsetpos(FILE *stream, const fpos_t *pos);

This function sets the file pointer associated with stream to a new
position.

I B.Tech COMPUTER PROGRAMMING UNIT-III 35


The following statements illustrate the fgetpos() and fsetpos()
functions:
FILE *fp;
long pos;
fp = fopen(“TEST.TXT”,”w+”);
fprinf(fp,”One Two Three Four”);
fseek(fp, -3 ,SEEK_END);
After executing the above statement, the situation is looking like the
following:

fgetpos(fp,&pos);
printf(“\n File position = %ld”,pos);
After executing the above statements, displays File Position = 16
pos = pos – 8;
fsetpos(fp,&pos);
After executing the above statement, the situation is looking like the
following:

printf(“\n File position = %ld”,pos);


printf(“\n Character at current position = %c”,fgetc(fp));
After executing the above statements, displays File Position = 9 and
Character at current position = T.

2.Explain about fread( ) and fwrite( ) functions in Files?

To read and write data types that are longer than 1 byte, the C file
system provides two functions:
fread( ) and fwrite( ). These functions allow the reading and writing of
blocks of any type of data.
Their prototypes are
size_t fread(void *buffer, size_t num_bytes, size_t count, FILE *fp);
Here,
I B.Tech COMPUTER PROGRAMMING UNIT-III 36
buffer Points to a block into which
data is read
num_bytes Length of each item read, in
bytes
count Number of items read
file_pointer Points to input stream

The fread()function writes data into a file. The following is the


declaration of fwrite() function:

size_t fwrite(const void *buffer, size_t num_bytes, size_t count, FILE


*fp);
Here,
buffer, Pointer to any object; the data
written at buffer.
num_bytes Length of each item data
count Number of data items to be
appended
file_pointer Points to output stream

For fread( ), buffer is a pointer to a region of memory that will receive


the data from the file. For fwrite( ), buffer is a pointer to the
information that will be written to the file.

One of the most useful applications of fread( ) and fwrite( ) involves


reading and writing userdefined
data types, especially structures. For example, given this structure,
struct struct_type {
float balance;
char name[80];
} cust;

the following statement writes the contents of cust to the file pointed
to by fp:
fwrite(&cust, sizeof(struct struct_type), 1, fp);

I B.Tech COMPUTER PROGRAMMING UNIT-III 37


/* Write some non-character data to a disk file
and read it back. */
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
FILE *fp;
double d = 12.23;
int i = 101;
long 1 = 123023L;
if((fp=fopen("test", "wb+"))==NULL)
{
printf(''Cannot open file.\n");
exit(1);
}
fwrite(&d, sizeof(double), 1, fp);
fwrite(&i, sizeof(int), 1, fp);
fwrite(&l, sizeof(long), 1, fp);
rewind(fp);
fread(&d, sizeof(double), 1, fp);
fread(&i, sizeof(int), 1, fp);
fread(&l, sizeof(long), 1, fp);
printf("%f %d %ld", d, i, 1);
fclose(fp);
return 0;
}

4. Explain Random-Access I/O files functions fseek( ) & ftell( ) in C


language?

You can perform random read and write operations using the ‘C’
language I/O system with the help of fseek( ), which sets the file
position indicator. Its prototype is shown here:
int fseek(FILE *fp, long int numbytes, int origin);
Here, fp is a file pointer returned by a call to fopen( ), numbytes is the
number of bytes from origin,

I B.Tech COMPUTER PROGRAMMING UNIT-III 38


which will become the new current position, and origin is one of the
following macros:

Origin Macro Name


Beginning of file SEEK_SET
Current position SEEK_CUR
End of file SEEK_END
Therefore, to seek numbytes from the start of the file, origin should be
SEEK_SET. To seek from
the current position, use SEEK_CUR, and to seek from the end of the
file, use SEEK_END. The
fseek( ) function returns zero when successful and a nonzero value if
an error occurs.
The following program illustrates fseek( ).
The following statements illustrate the fseek() function:
FILE *fp;
fp = fopen(“TEST.TXT”,”w+”);
fprinf(fp,”One Two Three Four”);
After executing the above statement, the contents “One Two Three
Four” are written to file “TEST.TXT”. The following figure illustrates
the above statements:

fseek(fp, -3 ,SEEK_END);
After executing the above statement, the situation is looking like the
following:

printf(“\n Current position character = %c”,fgetc(fp));


After executing the above statement, displays current position
character ‘o’.
fseek(fp,4,SEEK_SET);
After executing the above statement, the situation is looking like the
following:
I B.Tech COMPUTER PROGRAMMING UNIT-III 39
printf(“\n Current position character = %c”,fgetc(fp));
After executing the above statement, displays current position
character ‘T’.
fseek(fp,4,SEEK_CUR);
After executing the above statement, the situation is looking like the
following:

printf(“\n Current position character = %c”,fgetc(fp));


After executing the above statement, displays current position
character ‘T’.

It seeks to and displays the specified byte in the specified


file. Specify the filename and then the byte to seek to on the command
line.
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
FILE *fp;
if(argc!=3) {
printf(''Usage: SEEK filename byte\n");
exit(1);
}
if((fp = fopen(argv[1], "rb"))==NULL) {
printf("Cannot open file.\n");
exit(1);
}
if(fseek(fp, atol(argv[2]), SEEK_SET)) {
printf(''Seek error.\n");
exit(1);
}

I B.Tech COMPUTER PROGRAMMING UNIT-III 40


printf("Byte at %ld is %c.\n", atol(argv[2]), getc(fp));
fclose(fp);
return 0;
}
You can use fseek( ) to seek in multiples of any type of data by
simply multiplying the size of the
data by the number of the item you want to reach. For example,
assume a mailing list that consists of
structures of type addr (as shown earlier). To seek to the tenth address
in the file that holds the
addresses, use this statement:
fseek(fp, 9*sizeof(struct addr), SEEK_SET);
You can determine the current location of a file using ftell( ). Its
prototype is
long int ftell(FILE *fp);
It returns the location of the current position of the file associated with
fp. If a failure occurs, it
returns –1.
In general, you will want to use random access only on binary files.
The reason for this is simple.
Because text files may have character translations performed on them,
there may not be a direct
correspondence between what is in the file and the byte that it would
appear you want to seek to.
The only time you should use fseek( ) with a text file is when seeking
to a position previously
determined by ftell( ), using SEEK_SET as the origin.

The ftell() function


The ftell() function returns the current file pointer. The following is
the declaration of ftell() function:

long ftell(FILE *stream);

In the above statement ftell() returns the current file pointer for
stream. If the file is binary, the offset is measured in bytes from the
beginning of the file

I B.Tech COMPUTER PROGRAMMING UNIT-III 41


The following statements illustrate the ftell() function:

FILE *fp;
fp = fopen(“TEST.TXT”,”w+”);
The following figure illustrates the situation after executing the above
statements and the file is successfully opened:

pos = ftell(fp);
printf(“\nPosition = %ld”,pos);
After executing the above statements, display Position = 0
fprinf(fp,”One Two”);
After executing the above statement, the contents “One Two” are
written to file “TEST.TXT”. The following figure illustrates this:

pos = ftell(fp);
printf(“\nPosition = %ld”,pos);
After executing the above statements, display Position = 7
fprinf(fp,” Three Four”);
After executing the above statement, the contents “One Two” are
written to file “TEST.TXT”. The following figure illustrates this:

pos = ftell(fp);
printf(“\nPosition = %ld”,pos);
After executing the above statements, display Position = 18

5. Explain Formatted I/O functions fprintf( ) and fscanf( ) in C


language?

I B.Tech COMPUTER PROGRAMMING UNIT-III 42


In addition to the basic I/O functions already discussed, the C I/O
system includes fprintf( ) and
fscanf( ). These functions behave exactly like printf( ) and scanf( )
except that they operate with
files. The prototypes of fprintf( ) and fscanf( ) are
int fprintf(FILE *fp, const char *control_string, . . .);
int fscanf(FILE *fp, const char *control_string, . . .);
where fp is a file pointer returned by a call to fopen( ). fprintf( ) and
fscanf( ) direct their I/O
operations to the file pointed to by fp.
Here the “control string” is similar to that used with scanf () function.
On success, fscanf functions return the number of input fields
successfully scanned, converted, and stored and return value = EOF if
fscanf, attempts to read at end-of-file.

For example, consider the following statements :

FILE *stud;
int rno,m1,m2,m3;
char name[20];
stud = fopen(“student.dat”,”r”);
fscanf(stud,”%d %s %d %d %d”,&rno,&name,&m1,&m2,&m3);

The above code reads student details from the file “student.dat” and
details are stored in the corresponding variables. The following figure
illustrates this:

The pointer stud pointing to the file “student.dat” and the file is
opened in read mode. The fscanf statement reads the contents from

I B.Tech COMPUTER PROGRAMMING UNIT-III 43


the file and stores in the corresponding variable. That is , 101 stored
in rno, Rajiv stored in name, 54 stored in m1, 72 stored in m2 and 82
stored in m3.

If we use again the fscanf statement, then next student details are
stored in the corresponding variable as described above. The
following figure illustrates this:

Second fscanf statement reads the contents from the file and stores in
the corresponding variable. That is , 102 stored in rno, Rajesh stored
in name, 65 stored in m1, 45 stored in m2 and 71 stored in m3.

The following program displays all student details:

int main()
{
FILE *stud;
int rno,m1,m2,m3;
char name[20];
stud = fopen(“student.dat”,”r”);
while(fscanf(stud,”%d %s %d %d
%d”,&rno,&name,&m1,&m2,&m3))
{
printf(“\nRoll Number : %d”,rno);
printf(“\nName: %s”,name);
printf(“\nMarks – 1 : %d”,m1);
printf(“\nMarks – 2 : %d”,m2);
printf(“\nMarks – 3 : %d”,m3);
}
fclose(stud);
}

I B.Tech COMPUTER PROGRAMMING UNIT-III 44


Here the “control string” is similar to that used with printf () function.

On success, the fprintf functions return the number of bytes output.


On error, this function returns EOF.

For example, consider the following statements :

FILE *femp;
int eno;
char name[20];
float basic;
femp = fopen(“emp.dat”,”w”);
eno = 501;
strcpy(name,”Ganesh”);
basic = 9500.72;
fprintf(femp,”%d %s %f\n”,eno,name,basic);

The above code writes employee details into the file “emp.dat” and
details are stored into the file using variables eno, name and basic.
The following figure illustrates this:

The following code write one more employee details into “emp.dat”
FILE *femp;
int eno;
char name[20];
float basic;
femp = fopen(“emp.dat”,”w”);

eno = 501;

I B.Tech COMPUTER PROGRAMMING UNIT-III 45


strcpy(name,”Ganesh”);
basic = 9500.72;
fprintf(femp,”%d %s %f\n”,eno,name,basic);

eno = 502;
strcpy(name,”Krishna”);
basic = 10750.56;
fprintf(femp,”%d %s %f\n”,eno,name,basic);
The above code illustrated with figure in the following way:

The following program writes ‘n’ employee details into file


“emp.dat”:

int main()
{
int n, eno, i;
char name[20];
float basic;
FILE *femp;
femp = fopen(“emp.dat”,”w”);
printf(“\nEnter number of employees:”);
scanf(“%d”,&n);
printf(“\nEnter %d employee details:\n”);
for(i=0;i<n;i++)
{
printf(“\nSerial number : %d”,i+1);
printf(“\nEmployee Number :”);

I B.Tech COMPUTER PROGRAMMING UNIT-III 46


scanf(“%d”,&eno);
printf(“\nEmployee Name :”);
scanf(“%s”,&name);
printf(“\nBasic Salary :”);
scanf(“%f”,&basic);
}
fclose(femp);
}

/* fscanf() - fprintf() example */


#include <stdio.h>
#include <io.h>
#include <stdlib.h>
int main(void)
{
FILE *fp;
char s[80];
int t;
if((fp=fopen("test.txt", "w")) == NULL) {
printf(''Cannot open file.\n");
exit(1);
}
printf("Enter a string and a number: ");
fscanf(stdin, "%s%d", s, &t); /* read from keyboard */
fprintf(fp, "%s %d", s, t); /* write to file */
fclose(fp);
if((fp=fopen("test","r")) == NULL) {
printf("Cannot open file.\n");
exit(1);
}
fscanf(fp, "%s%d", s, &t); /* read from file */
fprintf(stdout, "%s %d", s, t); /* print on screen */
return 0;
}

I B.Tech COMPUTER PROGRAMMING UNIT-III 47

You might also like