You are on page 1of 33

UNIT III

1 a. Define Preprocessor directive? Explain the pre-processor directives in detail.


Ans:
• The preprocessors are the directives, which give instructions to the compiler to preprocess
the information before actual compilation starts.
• All preprocessor directives begin with #, and only white-space characters may appear
before a preprocessor directive on a line.
• Preprocessor directives are not C statements, so they do not end in a semicolon (;).

There are 4 main types of preprocessor directives:


• Macros
• File Inclusion
• Conditional Compilation
• Other directives

Macros:

Macros are piece of code in a program which is given some name. Whenever this name is
encountered by the compiler the compiler replaces the name with the actual piece of code.
Simple Macros:
• The ‘#define’ directive is used to define a macro. #include <stdio.h>
// macro definition #define LIMIT 5 int main()
{
int i;
for(i = 0; i < LIMIT; i++) {
printf(“%d”,i);
}
return 0; }

Macros with arguments: We can also pass arguments to macros. Macros defined
with arguments works similarly as functions.

#include <stdio.h>
// macro with parameter #define AREA(l, b) (l * b) int main()
{
int l1 = 10, l2 = 5, area;
area = AREA(l1, l2);
printf("Area of rectangle is: “,area);
return 0;
}
Macros with nested arguments:
#include <stdio.h>
// macro with parameter
#define M 5 #define N M+2 int main()
{
printf(“%d”,N);
return 0;
}
File Inclusion:
This type of preprocessor directive tells the compiler to include a file in the source code
program. There are two types of files which can be included by the user in the program.
• Header File or Standard files: These files contains definition of pre-defined functions like
sqrt(), strlen() etc.
• These files must be included for working with these functions.
• Different function are declared in different header files.
• For example standard I/O functions are in ‘stdio’ file whereas functions which perform
string operations are in ‘string’ file.
Syntax:
#include<file_name >
Ex: #include<string.h>
where file_name is the name of file to be included. The ‘<‘ and ‘>’ brackets tells the compiler to
look for the file in standard directory.
• user defined files: When a program becomes very large, it is good practice to divide it into
smaller files and include whenever needed. These types of files are user defined files. These files
can be included as: #include "filename"
Conditional Compilation:
Conditional Compilation directives are type of directives which helps to compile a specific
portion of the program or to skip compilation of some specific part of the program based on some
conditions.
• In C, a programmer can instruct the preprocessor whether or not to include certain section
of the code. This is accomplished using conditional directives.
• These are similar to if statements in syntax and usage. However, unlike if statements
which are executed during runtime, the conditional directives are executed before compilation by
the preprocessor.
• These directives are used whenever there is a need to compile a portion of the program
conditionally. It is also known as conditional compilation.
• The most common conditional directive #ifdef (spelt as if-defined) verifies if a given
identifier is defined or not.
• The syntax for its usage is :#ifdef identifier or #if defined (identifier).
• The source code following #ifdef will be compiled only if the given identifier is defined
either in the code or if it is provided as a compilation option as - identifier_name .
• The opposite of #ifdef is #ifndef, which is written as #ifndef identifier or #if !defined
(identifier).
• Consider the following example:
#if defined (MAX)
#define MIN 20
#else
#define MAX 100
#define MIN 200
#endif
• Here, MIN 20 will be defined only if the constant MAX is defined earlier than MIN
20. Else, both MAX and MIN will be defined with values 100 and 200 respectively.
#include <stdio.h>
#if defined (MAX)
#define MIN 20
#else
#endif
#define MAX 100
#define MIN 200
void main() {
printf("MAX value = %d, MIN value = %d\n", MAX, MIN);
}
Similar to if-else-if construct, we have a #if-#elif which is used in creating a chain of #if-else
statements that can be used to conditionally compile a portion of code.

The general syntax for #if, #elif, #else, #endif is given below:
#if expression1
statement_block1; #elif expression2
statement_block2;
#elif expression3
statement_block3;
#else
#endif
statement_block4;

#include <stdio.h>
#if BACKGROUND == 7
#define FOREGROUND 0
#elif BACKGROUND == 6
#define FOREGROUND 1
#else
#endif
#define FOREGROUND 6
void main() {
printf("FOREGROUND value = %d\n", FOREGROUND);
}
Program to find minimum of two numbers using macros
#include<stdio.h>
#define MIN(a,b) a>b?a:b
void main()
{
printf("Minimum is %d",MIN(34,4));
}

Other directives:
• The #undef directive “undefines” a symbolic constant or a macro identifier that has been
defined earlier; i.e., it negates the effects of a #define directive that may have appeared earlier in
the program.
• The #undef directive is used to remove values defined by #define directives so that they
can be redefined with new values.
• The format of #undef is #undef symbolic_name
• Given below is an example for #undef: #include <stdio.h>
#define TEMP 20
int main() {
printf("%d\n", TEMP);
#ifdef TEMP
#undef TEMP #define TEMP 99
Here, the code first prints 20 and then prints99.
#else
#endif
#define TEMP 999
printf("%d\n", TEMP); return 0;
}
1 b. Write a C program to merge the contents given two existing files into new file.
#include <stdio.h>
#include <stdlib.h>

void main()
{
// Open two files to be merged
FILE *fp1 = fopen("w.c", "r");
FILE *fp2 = fopen("ww.c", "r");
// Open file to store the result

FILE *fp3 = fopen("r.c", "w");


char c;
if (fp1 == NULL || fp2 == NULL || fp3 == NULL)
{
puts("Could not open files");
exit(0);

}
// Copy contents of first file to file3.txt
while ((c = fgetc(fp1)) != EOF)
fputc(c, fp3);
// Copy contents of second file to file3.txt
while ((c = fgetc(fp2)) != EOF)

fputc(c, fp3);
printf("Merged w.c and ww.c into r.c");
fclose(fp1);
fclose(fp2);
fclose(fp3);
}

2 a. Write a C program which copies one file to another, replacing all lowercase characters
with their uppercase equivalents.
#include <stdio.h>
#include<stdlib.h>

void main()
{
FILE *fp,*ft;
char ch;
fp=fopen("w.c","r");
ft=fopen("ww.c","w");

if(fp==NULL|| ft==NULL)
{
puts("Cannot open file");
exit(0);
}
while((ch=fgetc(fp))!=EOF)

{if(ch>=97&&ch<=122)
ch=ch-32;
fputc(ch,ft);
}
fclose(fp);
fclose(ft);

2 b. Explain Reading and writing on binary files.


Binary Files

1. Binary Files Contain Information Coded Mostly in Binary Format.


2. Binary Files are difficult to read for human.
3. Binary Files can be processed by certain applications or processors.
4. Only Binary File Processors can understood Complex FormattingInformation Stored in
Binary Format.
5. Humans can read binary files only after processing.
6. All Executable Files are Binary Files.
7. I/O operations are much faster with binary data.
8. Binary files are much smaller in size than text files.
9. Some data cannot be converted to character formats.

Creating and Reading and writing text and binary files

File Operations

In C, you can perform four major operations on the file, either text or binary:

1. Creating a new file


2. Opening an existing file
3. Closing a file
4. Reading from and writing information to a file

Working with files

When working with files, you need to declare a pointer of type file. This declaration is needed for
communication between the file and program.

Reading and writing to a binary file

Functions fread() and fwrite() are used for reading from and writing to a file on the disk
respectively in case of binary files.
Writing to a binary file

To write into a binary file, you need to use the function fwrite(). The functions takes four
arguments: Address of data to be written in disk, Size of data to be written in disk, number of such
type of data and pointer to the file where you want to write.

fwrite(address_data,size_data,numbers_data,pointer_to_file);
Example:
#include <stdio.h>
struct threeNum
{
int n1, n2, n3;
};

int main()
{
int n;
struct threeNum num;
FILE *fptr;
if ((fptr = fopen("C:\\program.bin","wb")) == NULL)
{
printf("Error! opening file"); // Program exits if the file pointer returns NULL.
exit(1);
}
for(n = 1; n < 5; ++n)
{
num.n1 = n;
num.n2 = 5n;
num.n3 = 5n + 1;
fwrite(&num, sizeof(struct threeNum), 1, fptr);
}
fclose(fptr);
return 0;
}

Reading from a binary file


Function fread() also take 4 arguments similar to fwrite() function as above.
fread(address_data,size_data,numbers_data,pointer_to_file);

Example:
#include <stdio.h>
struct threeNum
{
int n1, n2, n3;
};

int main()
{
int n;
struct threeNum num;
FILE *fptr;

if ((fptr = fopen("C:\\program.bin","rb")) == NULL)


{
printf("Error! opening file"); // Program exits if the file pointer returns NULL.
exit(1);
}
for(n = 1; n < 5; ++n)
{
fread(&num, sizeof(struct threeNum), 1, fptr);
printf("n1: %d\tn2: %d\tn3: %d", num.n1, num.n2, num.n3);
}
fclose(fptr);
return 0;
}

3 a. Write a C program to count the number of times a character occurs in a text file. The
file name and the character are supplied as command line arguments
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char *argv[])


{
FILE *finp = NULL;
FILE *output = NULL;
int letter; // character to be found
int ex=0; // character occurrence counter

if( argc!=4 )
{
printf( "pass correct way of command line arguments like inputfile outputfile character want
to search\n");
exit(0);
}
finp=fopen(argv[1], "r");

if( finp==NULL)
{
perror( "fopen for the input file failed" );
exit(0);
}
output=fopen(argv[2], "w");

if(output==NULL )
{
perror( "fopen for the output file failed" );
fclose( finp );
exit(0);
}

while( (letter = fgetc(finp) )!=EOF)


{
if( argv[3][0]==letter) /*From ASCII TABLE*/
{
ex++;
}

}
fprintf(output,"The search character is '%c' and it occurred %d times\n", argv[3][0], ex);
fclose(finp);
fclose(output);
return 0;
}

3 b. Explain about file positioning functions in C?


There is no need to read each record sequentially, if we want to access a particular record. C
supports these functions for random access file processing.

1. fseek()
2. ftell()
3. rewind()

The fseek function

We use the fseek() function to move the file position to a desired location.
Syntax:
fseek(fptr,offset,position);
Where, fptr is the file pointer. offset which is of type long, specifies the number of positions (in
bytes) to move in the file from the location specified by the position.
The position can take the following values.

 0 - The beginning of the file


 1 - The current position in the file
 2 - End of the file

Following are the list of operations we can perform using the fseek() function.

Operation Description

fseek(fptr, 0, 0) This will take us to the beginning of the file.

fseek(fptr, 0, 2) This will take us to the end of the file.

fseek(fptr, N, 0) This will take us to (N + 1)th bytes in the file.

fseek(fptr, N, 1) This will take us N bytes forward from the current position in the
file.
fseek(fptr, -N, 1) This will take us N bytes backward from the current position in the
file.

fseek(fptr, -N, 2) This will take us N bytes backward from the end position in the file.

Example:

#include <stdio.h>
int main ()
{
FILE *fp;
fp = fopen("file.txt","w+");
fputs("This is KMIT", fp);
fseek( fp, 7, SEEK_SET );
fputs(" C Programming Language", fp);
fclose(fp);
return(0);
}

Now the content in the file is changed to “This is C Programming Language”

The ftell function

The ftell() function tells us about the current position in the file (in bytes).
Syntax:
pos=ftell(fptr);
Where, fptr is a file pointer. pos holds the current position i.e., total bytes read (or written).
Example:
If a file has 10 bytes of data and if the ftell() function returns 4 then, it means that 4 bytes has
already been read (or written).
#include<stdio.h>
int main()
{
FILE *fp = fopen("test.txt","r");
char string[20];
fscanf(fp,"%s",string);
printf("%ld", ftell(fp));
return 0;
}

The rewind function

We use the rewind() function to return back to the starting point in the file.
Syntax:
rewind(fptr);
Where, fptr is a file pointer.
Example
#include<stdio.h>
#include<conio.h>
void main(){
FILE *fp;
char c;
clrscr();
fp=fopen("file.txt","r");
while((c=fgetc(fp))!=EOF)
{
printf("%c",c);
}
rewind(fp);//moves the file pointer at beginning of the file
while((c=fgetc(fp))!=EOF)
{
printf("%c",c);
}
fclose(fp);
getch();
}
The contents in file.txt is “ this is a simple text”
The output can be displayed as “this is a simple textthis is a simple text”.

4 a. List and explain various file read/write functions available in C with examples

File handling in C enables us to create, update, read, and delete the files stored on the local file
system through our C program. The following operations can be performed on a file.

o Creation of the new file


o Opening an existing file
o Reading from the file
o Writing to the file
o Deleting the file
Functions for file handling

There are many functions in the C library to open, read, write, search and close the file. A list of
file functions are given below:

No. Function Description

1 fopen() opens new or existing file

2 fprintf() write data into the file

3 fscanf() reads data from the file

4 fputc() writes a character into the file

5 fgetc() reads a character from file

6 fclose() closes the file

7 fgets() reads a string from file

8 fputs() writes an string in to the file

Opening a Text File in C


We use the fopen() function to create or open a file as mentioned earlier. It is pretty obvious that
creating or opening a file is the first step in file handling. Once the file has been created, it can be
opened, modified or deleted.

The basic syntax of opening a file is:

*fpointer = FILE *fopen(const char *file_name, const char *mode);


Here,

*fpointer is the pointer to the file that establishes a connection between the file and the program.

*file_name is the name of the file.

*mode is the mode in which we want to open our file.

Reading and Writing a Text File in C


 Input
 Output
 Input / Output
The input/output operations in a file help you read and write in a file.

The simplest functions used while performing operations on reading and writing characters in a
file are getc() and putc() respectively.

In order to read and write a set of data in a file, we use the fscanf() and fprintf() operators.

Mode Description

r opens a text file in read mode

w opens a text file in write mode

a opens a text file in append mode

r+ opens a text file in read and write mode

w+ opens a text file in read and write mode

a+ opens a text file in read and write mode

rb opens a binary file in read mode

wb opens a binary file in write mode

ab opens a binary file in append mode


rb+ opens a binary file in read and write mode

wb+ opens a binary file in read and write mode

ab+ opens a binary file in read and write mode

#include <stdio.h>

#include <stdlib.h>

int main()

printf("Welcome to PPS!\n\n");

char character;

FILE *fpointer;

fpointer = fopen("C:\\program.txt","w"); // Here "w" refers to write on file

if(fpointer == NULL)

printf("Error! The file does not exist.");

exit(0);

printf("Enter a character: ");


scanf("%c",&character);

fprintf(fpointer,"%c",character); // Use of fprintf() function

fclose(fpointer);

return 0;}

Reading Data for from an existing file


We can read content of a file in c using the fscanf() and fgets() and fgetc() functions. All are used
to read contents of a file. Let’s see the working of each of the function −
fscanf()
The fscanf() function is used to read character set i.e strings from the file. It returns the EOF, when
all the content of the file are read by it.
Syntax
int fscanf(FILE *stream, const char *charPointer[])
Parameters
FILE *stream: the pointer to the opened file.
const char *charPointer[]: string of character.
Example

#include <stdio.h>
int main(){
FILE * file;
char str[500];
if (file = fopen("hello.txt", "r")){
while(fscanf(file,"%s", str)!=EOF){
printf("%s", str);
}
}
else
printf("Error!”);
fclose(file);
return 0;
}
Output
LearnprogrammingattutorialsPoint
fgets()
The fget() function in C is used to read string from the stream.
Syntax
char* fgets(char *string, int length, FILE *stream)
Parameter
char *string: It is a string which will store the data from the string.
int length: It is an int which gives the length of string to be considered.
FILE *stream: It is the pointer to the opened file.
Example

#include <stdio.h>
int main(){
FILE * file;
char str[500];
if (file = fopen("hello.txt", "r")){
printf("%s", fgets(str, 50, file));
}
fclose(file);
return 0;
}
Output
Learn programming at tutorials Point
fgetc()
The fgetc() function in C is used to return a single character from the file. It gets a character from
the file and returns EOF at the end of file.
Syntax
char* fgetc(FILE *stream)
Parameter
FILE *stream: It is the pointer to the opened file.
Example

#include <stdio.h>
int main(){
FILE * file;
char str;
if (file = fopen("hello.txt", "r")){
while((str=fgetc(file))!=EOF)
printf("%c",str);
}
fclose(file);
return 0;
}
Output
Learn programming at tutorials Point
Writing Data to a file in C
We can write data to a file in C using the fprintf(), fputs(), fputc() functions. All are used to write
contents to a file.
Let’s see the working of each of the function −
fprintf()
The fprintf() function is used to write data to a file. It writes a set of characters in a file.
Syntax
int fprintf(FILE *stream, char *string[])
Parameters
FILE for *stream: It is the pointer to the opened file.
char *string[]: It is the character array that we want to write in the file.
Example
#include <stdio.h>
int main(){
FILE * file;
if (file = fopen("hello.txt", "w")){
if(fprintf(file, "tutorials Point”) >= 0)
printf("Write operation successful");
}
fclose(file);
return 0;
}
Output
Write operation successful
fputs()
The fputs() function in C can be used to write to a file. It is used to write a line (character line) to
the file.
Syntax
int fputs(const char *string, FILE *stream)
Parameters
Constant char *string[]: It is the character array that we want to write in the file.
FILE for *stream: It is the pointer to the opened file.
Example

int main(){
FILE * file;
if (file = fopen("hello.txt", "w")){
if(fputs("KMIT", file) >= 0)
printf("String written to the file successfully...");
}
fclose(file);
return 0;
}
Output
String written to the file successfully…
fputc()
The fputc() function is used to write a single character to the file.
Syntax
int fputc(char character , FILE *stream)
Parameters
char character : It is the character that we want to write in the file.
FILE for *stream: It is the pointer to the opened file.
Example
#include <stdio.h>
int main(){
FILE * file;
if (file = fopen("hello.txt", "w")){
fputc('T', file);
}
fclose(file);
return 0;
}
Output
‘T’ is written to the file.
fclose()
The fclose() function is used to close the open file. We should close the file after performing
operations on it to save the operations that we have applied to it.
Syntax
fclose(FILE *stream)
Parameters
FILE for *stream: It is the pointer to the opened file.
Example

#include <stdio.h>
int main(){
FILE * file;
char string[300];
if (file = fopen("hello.txt", "a+")){
while(fscanf(file,"%s", string)!=EOF){
printf("%s", string);
}
fputs("Hello", file);
}
fclose(file);
return 0;
}
Output
Learnprogramming

4 b. Discuss how to read and write on text file?

Text files are the normal .txt files. You can easily create text files using any simple text editors
such as Notepad.

When you open those files, you'll see all the contents within the file as plain text. You can easily
edit or delete the contents.

They take minimum effort to maintain, are easily readable, and provide the least security and takes
bigger storage space.Reading and writing to a text file

For reading and writing to a text file, we use the functions fprintf() and fscanf().

Writing to a text file


Example
#include <stdio.h>
int main()
{
int num;
FILE *fptr;
fptr = fopen("C:\\program.txt","w");
if(fptr == NULL)
{
printf("Error!");
exit(1);
}
printf("Enter num: ");
scanf("%d",&num);
fprintf(fptr,"%d",num);
fclose(fptr);
return 0;
}
Reading from a text file
Example

#include <stdio.h>
int main()
{
int num;
FILE *fptr;
if ((fptr = fopen("C:\\program.txt","r")) == NULL){
printf("Error! opening file"); // Program exits if the file pointer returns NULL.
exit(1);
}
fscanf(fptr,"%d", &num);
printf("Value of n=%d", num);
fclose(fptr);
return 0;
}

5 a. Write a C program to display the contents of a file to a standard output device.


#include <stdio.h>
int main()
{
FILE *fptr;
char filename[100], c;
printf("Enter the filename to open : ");
scanf("%s", filename);//enter any existing file name
// Open file
fptr = fopen(filename, "r");
if (fptr == NULL)
{
printf("Cannot open file \n");
return 0;
}
// Read contents from file
c = fgetc(fptr);
while (c != EOF)
{
printf ("%c", c);
c = fgetc(fptr);
}
fclose(fptr);
return 0;
}
5 b. Write the concept of a file.
A File can be used to store a large volume of persistent data.
Types of Files
When dealing with files, there are two types of files you should know about:

1. Text files
2. Binary files
1. Text files
Text files are the normal .txt files. You can easily create text files using any simple text editors
such as Notepad.
When you open those files, you'll see all the contents within the file as plain text. You can easily
edit or delete the contents.

They take minimum effort to maintain, are easily readable, and provide the least security and takes
bigger storage space.

2. Binary files
Binary files are mostly the .bin files in your computer.
Instead of storing data in plain text, they store it in the binary form (0's and 1's).

They can hold a higher amount of data, are not readable easily, and provides better security than
text files.

Like many other languages 'C' provides following file management functions,

 Creation of a file
 Opening a file
 Reading a file
 Writing to a file
 Closing a file

Following are the most important file management functions available in 'C,'

function purpose

fopen () Creating a file or opening an existing file

fclose () Closing a file

fprintf () Writing a block of data to a file

fscanf () Reading a block data from a file


getc () Reads a single character from a file

putc () Writes a single character to a file

getw () Reads an integer from a file

putw () Writing an integer to a file

fseek () Sets the position of a file pointer to a specified location

ftell () Returns the current position of a file pointer

rewind () Sets the file pointer at the beginning of a file

6 a. Explain about ferror(), feof(), clearerr() functions.


feof() function is a file handling function in C programming language which is used to find the
end of a file.
Declaration: int feof(FILE *fp)
feof functions is used to find the end of a file. In a C program, we use feof() function as below.
feof(fp);

where,
fp – file pointer
# include <stdio.h>
int main( )
{
FILE *fp ;
char c ;
printf( "Opening the file test.c in read mode" ) ;
fp = fopen ( "test.c", "r" ) ; // opening an existing file
if ( fp == NULL )
{
printf ( "Could not open file test.c" ) ;
return 1;
}
printf( "Reading the file test.c" ) ;
while ( 1 )
{
c = fgetc ( fp ) ; // reading the file
if( feof(fp) )
break ;
printf ( "%c", c ) ;
}
printf("Closing the file test.c as end of file is reached.");
fclose ( fp ) ; // Closing the file
return 0;
}

The function ferror() is used for checking the errors in the stream.

Syntax:
int ferror(FILE *stream);

This function returns 0 if there are no errors and a value if there are some errors.

Following are the functions which are used for detecting the errors:

Functions Syntax Description


clearerr() void clearerr(FILE It is used for clearing the end-of-file and error indicators for the
*stream); stream.

perror() void perror(char It stands for the print error.


*msg);

6 b. Write a C program to copy the data from one file to another file.
#include <stdio.h>
#include<stdlib.h>
void main()
{
FILE *fp,*ft;
char ch;

fp=fopen("file1.txt","r");
ft=fopen("file2.txt","w");
if(fp==NULL)
{
puts("Cannot open file");
exit(0);
}

if(ft==NULL)
{
puts("Cannot open file");
}
while((ch=fgetc(fp))!=EOF)
{

fputc(ch,ft);
}
fclose(fp);
fclose(ft);
fp=fopen("file2.txt","r");
while((ch=fgetc(fp))!=EOF)

{
putchar(ch);
}
fclose(fp);
}

7 a. Write a C program read and write the content of the file using fprintf( ) and fscanf( )
functions.
#include<stdio.h>
#include<conio.h>
struct emp
{
char name[10];
int age;
};
main()
{
struct emp e;
FILE *p,*q;
p = fopen(“one.txt”, “a”);
q = fopen(“one.txt”, “r”);
printf(“Enter Name and Age”);
scanf(“%s %d”, e.name, &e.age);
fprintf(p,“%s %d”, e.name, e.age);
fclose(p);
do
{
fscanf(q,”%s %d”, e.name, e.age);
printf(“%s %d”, e.name, e.age);
}
while(!eof(q));
}

7 b. Explain about fread(), fwrite, fprintf(), fscanf() functions?


read() and fwrite():
size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);
size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream);
The functions fread/fwrite are used for reading/writing data from/to the file opened by fopen
function. These functions accept three arguments. The first argument is a pointer to buffer used
for reading/writing the data. The data read/written is in the form of ‘nmemb’ elements each ‘size’
bytes long.

In case of success, fread/fwrite return the number of bytes actually read/written from/to the stream
opened by fopen function. In case of failure, a lesser number of byes (then requested to read/write)
is returned.
fscanf()
Declaration: int fscanf(FILE *fp, const char *format, …)
fscanf() function is used to read formatted data from a file. In a C program, we use fscanf() as
below.

fscanf (fp, “%d”, &age);


Where, fp is file pointer to the data type “FILE”.
Age – Integer variable
This is for example only. You can use any specifiers with any data type as we use in normal
scanf() function.
fprintf()
Declaration: int fprintf(FILE *fp, const char *format, …)
fprintf() function is used to write formatted data into a file. In a C program, we use fprinf() as
below.
fprintf (fp, “%s %d”, “var1”, var2);

Where, fp is file pointer to the data type “FILE”.


var1 – string variable
var2 – Integer variable
This is for example only. You can use any specifiers with any data type as we use in normal printf()
function.

8. a. Write a program to store students information (names, marks) into a file and print the
information from the file.
#include<stdio.h>
int main() {
char name[50];
int marks,i,n;

printf("Enter number of students: ");


scanf("%d",&n);
FILE *fptr;
fptr=(fopen("student.txt","w"));
if(fptr==NULL) {
printf("Error!");

return;
}
for (i=0;i<n;++i) {
printf("For student%d\nEnter name: ",i+1);
scanf("%s",name);

printf("Enter marks: ");


scanf("%d",&marks);
fprintf(fptr,"\nName: %s \nMarks=%d \n",name,marks);
}
fclose(fptr);
fptr=(fopen("student.txt","r"));

if(fptr==NULL) {
printf("Error!");
return;
}
for (i=0;i<n;++i) {
fscanf(fptr,"\nName: %s \nMarks=%d \n",name,&marks);

printf("student %d name: %s\n",i+1,name);


printf("student marks: %d\n",marks);

}
fclose(fptr);
return 0;

8 b. Differentiate between text and binary files.

 A text file stores data in the form of alphabets, digits and other special symbols by storing
their ASCII values and are in a human readable format. For example, any file with a .txt,
.c, etc extension. Whereas, a binary file contains a sequence or a collection of bytes which
are not in a human readable format. For example, files with .exe, .mp3, etc extension. It
represents custom data.
 A small error in a textual file can be recognized and eliminated when seen. Whereas, a
small error in a binary file corrupts the file and is not easy to detect.
 Since the data is not human readable it also adds to the security of the content as one might
not be able to get data if the structure is not known.

9 a. Write a ‘C’ program to count the number of characters, words, lines in a file.
#include <stdio.h>
#define MAX_LEN 1024
int main() {
char ch;

int char_count = 0, word_count = 0, line_count = 0;


int in_word = 0;
char file_name[MAX_LEN];
FILE *fp;
printf("Enter a file name: ");
scanf("%s", file_name);

fp = fopen(file_name, "r");
if(fp == NULL) {
printf("Could not open the file %s\n", file_name);
return 1;
}
while ((ch = fgetc(fp)) != EOF) {

char_count++;
if(ch == ' ' || ch == '\t' || ch == '\0' || ch == '\n') {
if (in_word) {
in_word = 0;
word_count++;
}

if(ch = '\0' || ch == '\n') line_count++;


} else {
in_word = 1;
}

printf("In the file %s:\n", file_name);


printf("Number of characters: %d.\n", char_count);
printf("Number of words: %d.\n", word_count);
printf("Number of lines: %d.\n", line_count);

return 0;
}

9 b. Explain the concept of streams and types of streams in C.


A stream is a sequence of characters with functions to take characters out of one end, and put
characters into the other end. In the case of input/output streams, one end of the stream is connected
to a physical I/O device such as a keyboard or display. If it is a console output stream, your program
puts characters into one end of the stream, and the display system takes characters out of the other
and puts them on the screen. If it is a console input stream, the keyboard puts characters into one
end of the stream, and your program takes characters out of the other and stores the results in
variables in the program. If no characters are waiting in the input stream, your program must wait
until you supply some by typing on the keyboard. File streams follow the same principle, except
that the file system is attached to the other end of the stream.
Types of Streams in C

• Standard input stream is called "stdin" and is normally connected to the keyboard
• Standard output stream is called "stdout" and is normally connected to the display screen.
• Standard error stream is called "stderr" and is also normally connected to the screen.

You might also like