14 Files – Programming in C, 3/e, 3rd Edition

CHAPTER 14

Files

Chapter Outline

14.1  INTRODUCTION OF A FILE

A file is nothing but collection of records. Record is group of related data items. All data items ­related to students, employees, customers etc is nothing but records. In other words, file is a collection of numbers, symbols & text placed onto the secondary devices like hard disk, pen drive, compact disk etc. Files are stored permanently on to the disk and one can access them for further monitoring/­ processing if needed. In the next few paragraphs/sections, we will learn how files can be read and modified as per requirements.

14.2  DEFINITION OF FILE

A file can be considered as a stream of characters. A file can be a set of records that can be accessed through the set of library functions. These functions are available in stdio.h.

The data can be stored in secondary storage devices such as floppy or hard disk. Figure 14.1 shows communication between keyboard, Ram and Secondary device.

As shown in the figure data, read from keyboard is stored in variables. Variables are created in RAM (type of primary memory). Variables hold the data temporarily in the program. On the execution of a program and manipulating data the original data may be lost. It is needed to store the data permanently on to the secondary devices. On applying disk I/O operations, all variables created in RAM can be stored to the secondary storage device such as hard disk or floppy disk.

Figure 14.1 Communication between program, file and output device

In Figure 14.1, a floppy disk is shown. It is also possible to read data from it or secondary storage devices. When data is read from such devices it is placed in the RAM and then using console I/O operations it is transferred to screen.

A file is nothing but the accumulation of data stored on the disk created by the user. The programmer assigns file name. The file names are unique and are used to identify the file. No two files can have the same names in the same directory. There are various kinds of files such text files, program files, data files, executable file and so on. Data files contain a combination of numbers, alphabets, symbols called data.

Data communication can be performed between program and output devices or files and program. File streams are used to carry the communication among above-mentioned devices. The stream is nothing but the flow of data in bytes in sequence. If data is received from input devices in sequence then it is called source stream and when the data is passed to output devices then it is called destination stream. Figure 14.2 shows the input and output streams. The input stream brings data to the program and the output stream collects data from program. In this way, input stream extracts data from the file and transfers it to the program while the output stream stores the data into the file provided by the program.

Figure 14.2 Input and output streams

14.3  STREAMS AND FILE TYPES

Data flow from program to a file or vice versa is done with stream, which is a series of bytes. In order to perform I/O operations on the files, reading or writing a file is done with streams. Reading and writing data is done with streams. The streams are designed to allow the user to access the files efficiently. A stream is a file and using physical device like keyboard, information is stored in the file. The FILE object uses these devices such as keyboard, printer and monitor.

The FILE object contains all the information about stream like current position, pointer to any buffer, error and end of file (EOF). Using this information of object, C program uses pointer, which is returned from the stream function fopen(). A function fopen() is used for opening a file.

14.3.1  File types

There are two types of files. (1) Sequential file and (2) Random accesses file.

  1. Sequential file: In this type of file, data are kept sequentially. If we want to read the last record of the file then it is expected to read all the records before it. It takes more time for accessing the records. Or if we desire to access the 10th record then the first nine records should be read sequentially for reaching the 10th record.
  2. Random access file: In this type, data can be read and modified randomly. If the user desires to read the last records of a file, directly the same records can be read. Due to random access of data, it takes access time less as compared to the sequential file.
14.4  Steps for File Operations

Most of the compilers support file handing functions. C language also supports numerous file-handling functions that are available in standard library. A few of these functions are listed in Table 14.1. All the functions that are supported by C for file handling are not listed. The library functions supported by C are very exhaustive ones and hence, all functions are not provided. One should check the C library functions before using them.

Table 14.1 File functions

Function

Operation

fopen()

Creates a new file for read/write operation.

fclose()

Closes a file associated with file pointer.

closeall()

Closes all files opened with fopen().

fgetc()

Reads the character from current pointer position and advances the pointer to the next character.

getc()

Same as fgetc().

fprintf()

Writes all types of data values to the file.

fscanf()

Reads all types of data values from a file.

putc()

Writes characters one-by-one to a file.

fputc()

Same as putc().

gets()

Reads a string from the file.

puts()

Writes a string to the file.

putw()

Writes an integer to the file.

getw()

Reads an integer from the file.

fread()

Reads structured data written by fwrite() function.

fwrite()

Writes block of structured data to the file.

fseek()

Sets the pointer position anywhere in the file.

feof()

Detects the end of file.

ferror()

Reports error occurred while read/write operations.

perror()

Prints compilers error messages along with user-defined messages.

ftell()

Returns the current pointer position.

rewind()

Sets the record pointer at the beginning of the file.

unlink()

Removes the specified file from the disk.

rename()

Changes the name of the file.

14.4.1  Opening of File

A file has to be opened before read and write operations. Opening of a file creates a link between the operating system and the file functions. The name of the file and its mode of operation are to be indicated to the operating system. This important task is carried out by the structure FILE that is defined in stdio.h header file. So this file must be included.

When a request is made to the operating system for opening a file, it does so by granting the request. If request is granted then the operating systems points to the structure FILE. In case, the request is not granted, it returns NULL. That is why the following declaration before opening of the file is to be made:

FILE *fp

where fp is the file pointer.

Each file that we open has its own FILE structure. The information that is there in the file may be its current size, and its location in memory. The only one function to open a file is fopen().

Syntax:

FILE *fp;

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

Here fp is a pointer variable that contains the address of the structure FILE that has been defined in the header file stdio.h. It is necessary to write FILE in the uppercase. The function fopen() will open a file ‘data.txt’ in read mode. The C compiler reads the contents of the file because it finds the read mode (“r”). Here, “r” is a string and not a character. Hence, it is enclosed with double quotes and not with single quotes.

The fopen() performs the following important tasks:

  1. It searches the disk for opening of the file.
  2. In case the file exists, it loads the file from the disk into memory. If the file is found with huge contents then it loads the file part by part.
  3. If the file is not existing this function returns a NULL. NULL is a macro defined in the header file ‘stdio.h‘. This indicates that it is unable to open a file. There may be the following reasons for failure of fopen() functions: (A) when the file is in protected or hidden mode and (B) the file may be in use by another program.
  4. It locates a character pointer, which points the first character of the file. Whenever a file is opened the character pointer points to the first character of the file.

14.4.2  Reading a File

Once the file is opened using fopen(), its contents are loaded into the memory (partly or wholly). The pointer points to the very first character of the file. The fgetc() function is used to read the contents of the file. The syntax for fgetc() is as follows:

ch=fgetc(fp);

where fgetc() reads the character from current pointer position and advances the pointer position so that the next character is pointed. The variable ch contains the character read by fgetc(). There are also other functions to read the contents of file, which are explained below.

14.4.3  Closing a File

The file that is opened from the fopen() should be closed after the work is over, i.e. we need to close the file after reading and writing operations. In other words, the file must be closed after operations. Also, whenever an opened file needs to be reopened in other mode in such a case also the opened file must be closed first. Closing the file enables to wash out all its contents from the RAM buffer and further the link is disconnected from the file.

Example:

The function to close a file is

fclose(fp);

This statement closes the file associated with file pointer fp. This function closes one file at a time. In order to close all files function syntax used is as follows:

fcloseall();

This function closes all the opened files and returns the number of files closed. It does not require any argument.

14.4.4  Text Modes

 

1. w(write)

This mode opens a new file on the disk for writing. If the file already exists, its contents will be over-written without confirmation. If the concerned file is not found, a new file is created.

Syntax:

fp=fopen (“data.txt”,“w”);

Here data.txt is the file name and “w” is the mode.

 

2. r(read)

This mode searches a file and if it is found the same is loaded into the memory for reading from the first character of the file. The file pointer points to the first character and reading operation begins. If the file does not exist then compiler returns NULL to the file pointer. Using pointer with the if statement we can prompt the user regarding failure of operation. The syntax of read mode is as follows:

Syntax:

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

if(fp==NULL)

printf(“File does not exist”);

 

OR

if(fp=(fopen(“data.txt”,“r”))==NULL)

printf(“File does not exist”);

Here data.txt is opened for reading only. If the file does not exist the fopen() returns NULL to file pointer ‘fp’. Using the NULL value of fp with the if statement, we can prompt the user for failure of fopen() function. A program is illustrated below giving the use of “w” and “r” modes.

14.1  Write a program to write data to text file and read it.

 

# include <stdio.h>

# include <conio.h>

# include <process.h>

void main()

{

FILE *fp;

char c=‘ ’;

clrscr();

fp=fopen(“data.txt”,“w”);

if(fp==NULL)

{

  printf(“Can not open file”);

  exit(1);

}

printf(“Write data & to stop press ‘.’ :”);

while(c!=‘.’)

{

  c=getche();

  fputc(c,fp);

}

fclose(fp);

printf(“\n Contents read :”);

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

while(!feof(fp))

printf(“%c”,getc(fp));

}

OUTPUT:

Write data & to stop press ‘.’: ABCDEFGHIJK.

Contents read: ABCDEFGHIJK.

Explanation:

In the above program, the file named “data.txt” is opened in write mode. The characters are read from the keyboard and stored in variable ‘c’. Using fputc() the characters are written to a file until ‘.’ (dot) is pressed. The same file is closed and then it is reopened in read mode. On reopening of the file, character pointer sets to the beginning of the file. The contents of the file will be displayed on the screen using getc().

 

3. a(append)

This mode opens a pre-existing file for appending data. The data appending process starts at the end of the opened file. The file pointer points to the last character of the file. If the file does not exist, then a new file is opened, i.e. if the file does not exist then the mode of “a” is the same as “w”. Due to some or other reasons if file is not opened in such a case NULL is returned. File opening may be impossible due to insufficient space on to the disk and some other reasons. Syntax for opening a file with append mode is a follows:

Syntax:

fp=fopen(“data.txt”,“a”);

Here, if data.txt file already exists, it will be opened. Otherwise a new file will be opened with the same name.

14.2  Write a program to open a pre-existing file and add information at the end of file. Display the contents of the file before and after appending.

 

# include <stdio.h>

# include <conio.h>

# include <process.h>

void main()

{

FILE *fp;

char c;

clrscr();

printf(“Contents of file before appending :\n”);

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

while(!feof(fp))

{

  c=fgetc(fp);

  printf(“%c”,c);

}

fp=fopen(“data.txt”,“a”);

if(fp==NULL)

{

  printf(“File can not appended”);

  exit(1);

}

printf(“\n Enter string to append :”);

while(c!=‘.’)

{

  c=getche();

  fputc(c,fp);

}

fclose(fp);

printf(“\n Contents of file After appending :\n”);

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

while(!feof(fp))

{

  c=fgetc(fp);

  printf(“%c”,c);

}

}

OUTPUT:

Contents of file before appending :

String is terminated with ‘\0’.

Enter string to append :

This character is called as NULL character.

Contents of file After appending :

String is terminated with ‘\0’.

This character is called as NULL character.

4. w+ (Write + read)

This mode starts for file search operation on the disk. In case the file is found, its contents are destroyed. If the file is not found, a new file is created. It returns NULL if it fails to open the file. In this file mode, new contents can be written and thereafter reading operation can be done.

Example:

fp=fopen(“data.txt”,“w+”);

In the above example, data.txt file is open for reading and writing operations.

14.3  Write a program to use w+ mode for writing and reading of a file.

 

# include <stdio.h>

# include <conio.h>

# include <process.h>

void main()

{

FILE *fp;

char c=’ ‘;

clrscr();

fp=fopen(“data.txt”,“w+”);

if(fp==NULL)

{

  printf(“Can not open file”);

  exit(1);

}

printf(“Write data & to stop press ‘.’ :”);

while(c!=‘.’)

{

  c=getche();

  fputc(c,fp);

}

rewind(fp);

printf(“\n Contents read :”);

while(!feof(fp))

printf(“%c”,getc(fp));

}

OUTPUT:

Write data & to stop press ‘.’: ABCDEFGHIJK.

Contents read : ABCDEFGHIJK.

Explanation:

Instead of using separate read and write modes, one can use w+ mode to perform both the operations. Hence, in the above program w+ is used. At first writing operation is done. It is not essential to close the file for reading the contents of it. We need to set the character pointer at the beginning. Hence, rewind() function is used. The advantage of using w+ is to reduce the number of statements.

 

5. a+ (append + read)

In this file operation mode the contents of the file can be read and records can be added at the end of file. A new file is created in case the concerned file does not exist. Due to some or the other reasons if a file is unable to open then NULL is returned.

Example:

fp=fopen(“data.txt”,“a+”);

Here data.txt is opened and records are added at the end of file without affecting the previous contents.

14.4  Write a program to open a file in append mode and add new records in it.

 

# include <stdio.h>

# include <conio.h>

# include <process.h>

void main()

{

FILE *fp;

char c=‘ ’;

clrscr();

fp=fopen(“data.txt”,“a+”);

if(fp==NULL)

{

  printf(“Can not open file”);

  exit(1);

}

printf(“Write data & to stop press ‘.’ :”);

while(c!=‘.’)

{

  c=getche();

  fputc(c,fp);

}

printf(“\n Contents read :”);

rewind(fp);

while(!feof(fp))

printf(“%c”,getc(fp));

}

OUTPUT:

Write data & to stop press ‘.’ : This is append and read mode.

Contents read : This is append and read mode.

Explanation:

In the above program, a file named “data.txt” is opened in read and append mode (a+). If a file does not exist, a new file is created. Write operation is performed first and the contents are read thereafter. Before reading character pointer is set at the beginning of file using rewind().

Notes:

  1. In case read operation is done after write operation, character pointer should be set to beginning of the file using rewind().
  2. In case write/append operation is done after read operation, it is not essential to set the character pointer at the beginning of file.

6. r+ (read + write)

This mode is used for both reading and writing. We can read and write the record in the file. If the file does not exist, the compiler returns NULL to the file pointer. It can be written as follows:

Example:

fp=fopen(“data.dat”,“r+”);

if(fp==NULL)

printf(“File not found”);

In the above example, data.dat is opened for the read and write operation. If fopen() fails to open the file then it returns NULL. The if statements check the value of file pointer fp; and if it ­contains NULL then a message is printed and program terminates.

14.5  Write a program to open a file in read/write mode in it. Read and write new information in the file.

 

# include <stdio.h>

# include <conio.h>

# include <process.h>

void main()

{

FILE *fp;

char c=‘ ’;

clrscr();

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

if(fp==NULL)

{

  printf(“Can not open file”);

  exit(1);

}

printf(“\n Contents read :”);

while(!feof(fp))

printf(“%c”,getc(fp));

printf(“Write data & to stop press ‘.’ :”);

while(c!=‘.’)

{

  c=getche();

  fputc(c,fp);

}

}

OUTPUT:

Contents read: Help me.

Write data & to stop press ‘.’: I am in trouble.

Explanation:

In the above example, file is opened in read and write mode (r+). The getc() function reads the contents of file which is printed through printf() function. The getche() function reads characters from the keyboard and the read characters are written to the file using fputc() function.

14.4.5  Binary Modes

When numerical data is to be transferred to disk from RAM, the data occupies more memory space on disk. For example, a number 234567 needs 3 bytes memory space in RAM and when transferred to disk requires 6 bytes memory space. For each numerical digit one byte space is needed. Hence, total requirement for the number 234567 would be 6 bytes. Thus, text mode is inefficient for storing large amount of numerical data because space occupation by it is large. Only solution to this inefficient memory use is to open a file in binary mode, which takes lesser space than text mode. Few binary modes are described below.

 

1. wb(write) :

This mode opens a binary file in write mode.

Example:

fp=fopen(“data.dat”,“wb”);

Here data.dat file is opened in binary mode for writing.

 

2. rb(read) :

This mode opens a binary file in read mode.

Example:

fp=fopen(“data.dat”,“rb”);

Here data.dat file is opened in binary mode for reading.

14.6  Write a program to open a file for read/write operation in binary mode. Read and write new information in the file.

 

# include <stdio.h>

# include <conio.h>

# include <process.h>

void main()

{

FILE *fp;

char c=‘ ’;

clrscr();

fp=fopen(“data.dat”,“wb”);

if (fp==NULL)

{

  printf(“Can not open file”);

  exit(1);

}

printf(“Write data & to stop press ‘.’ :”);

while(c!=’.’)

{

  c=getche();

  fputc(c,fp);

}

fclose(fp);

fp=fopen(“data.dat”,“rb”);

printf(“\n Contents read :”);

while(!feof(fp))

printf(“%c”,getc(fp));

}

Explanation:

This program is the same as explained earlier. The only difference is that the file-opening mode is binary.

 

3. ab(append):

This mode opens a binary file in append mode i.e. data can be added at the end of file.

Example:

fp=fopen(“data.dat”,“ab”);

Here data.dat file is opened in append mode.

 

4. r+b(read + write):

This mode opens a pre-existing file in read and write mode, i.e. a file can be read and written.

Example:

fp=fopen(“data.dat”,“r+b”);

Here, the file “data.dat” is opened for reading and writing in binary mode.

 

5. w+b(read + write):

This mode creates a new file in read and write mode.

Example:

fp=fopen(“data.dat”,“w+b”);

Here, the file “data.dat” is created for reading and writing in binary mode.

 

6. a+b(append+ write):

This mode opens a file in append mode, i.e. data can be written at the end of file. If file does not exist then a new file is created.

Example:

fp=fopen(“data.dat”,”a+b”);

Here the file “data.dat” is opened in append mode and data can be written at the end of file.

14.5  FILE I/O

1. fprintf() :

This function is used for writing characters, strings, integers, floats, etc. to the file. The fprint() function is used for writing characters in various formats. Hence, this function is called the formatted function. It contains one more parameter that is file pointer, which points the opened file.

The operation of fprintf() and fscanf() functions are identical to that of printf() and scanf() except that former function works with files.

The format of fprintf() is as follows:

fprintf() (fp,“control string”,text);

where fp is a file pointer associated with an opened file in write mode. The text can be variables, constants or strings.

A programming example on this function is as follows.

14.7  Write a program to open a text file and write some text using fprintf() function. Open the file and verify the contents.

 

# include <stdio.h>

# include <conio.h>

void main()

{

FILE *fp;

char text[30];

fp=fopen(“Text.txt”,“w”);

clrscr();

printf(“Enter Text Here :”);

gets(text);

fprintf(fp,“%s”,text);

fclose(fp);

}

OUTPUT:

Enter Text Here: Have a nice day.

Explanation:

In the above program, fprintf() function writes the string to the file pointed by fp. The string is collected through gets() function into character array name[30].

 

2. fscanf() :

This function reads characters, strings, integer, floats, etc. from the file pointed by file pointer. This is also a formatted function. A program is illustrated below based on this.

The syntax of this function is as follows:

fscanf(fp,“control string”,text);

With this statement reading operations from the designated file is done.

14.8  Write a program to enter data into the text file and read the same. Use “w+” file mode. Use fscanf() to read the contents of the file.

 

# include <stdio.h>

# include <conio.h>

void main()

{

FILE *fp;

char text[15];

int age;

fp=fopen(“Text.txt”,“w+”);

clrscr();

printf(“Name\t AGE\n ”);

scanf(“%s %d”,text,&age);

fprintf(fp,“%s %d”, text,age);

printf(“Name\t AGE\n ”);

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

printf(“%s\t%d\n”, text,age);

fclose(fp);

}

OUTPUT:

Name    AGE

AMIT    12

Name    AGE

AMIT     12

Explanation:

In the above program, fscanf() reads the data from the file named “Text.txt”.

 

3. getc() :

This function reads a single character from the opened file and moves the file pointer. It returns EOF, if end of file is reached.

For example, in the statement c=getc(f);, a character is read from the file whose file pointer is f. A program is illustrated below on the basis of this function.

14.9   Write a program to read the contents of the file using getc() function.

 

# include <stdio.h>

# include <process.h>

# include <conio.h>

void main()

{

FILE *f;

char c;

clrscr();

f=fopen(“list.txt”,“r”);

if(f==NULL)

{

  printf(“\nCannot open file”);

  exit(1);

}

while((c=getc(f))!=EOF)

printf(“%c”,c);

fclose(f);

}

OUTPUT:

aman

akash

amit

ajay

ankit

Explanation:

In the above program, the getc(f) reads character from the file “list.txt”. Some text is to be written before reading this file.

Example:

 

4. putc():

This function is used to write a single character into a file. If an error occurs then it returns EOF.

For example, in the statement putc(c,fp);, a character contained in character variable c is written in the file whose file pointer is fp. A program is illustrated below on the basis of this function.

14.10  Write a program to write some text into the file using putc() function.

 

# include <stdio.h>

# include <conio.h>

void main()

{

int c;

FILE *fp;

clrscr();

printf(“\n Enter Few Words ‘*’ to Exit\n”);

fp=fopen(“words.doc”,“w”);

while( (c=getchar())!=‘*’)

putc(c,fp);

fclose(fp);

}

OUTPUT:

Enter Few Words ‘*’ to Exit

This is saved into the file *

Explanation:

The putc() function writes character read through getchar() in the file “words. doc”. User should enter ‘’ to stop reading character.

 

5. fgetc() :

This function is similar to the getc() function. It also reads a character and increments the file pointer position. If any error or end of file is reached then it returns EOF.

14.11  Write a program to read a C program file and count the following in the complete program:

  1. Total number of statements.
  2. Total number of included files.
  3. Total number of blocks and brackets.

 

# include <stdio.h>

# include <conio.h>

void main()

{

FILE *fs;

int i=0,x,y,c=0,sb=0,b=0;

clrscr();

fs=fopen(“PRG2.C”,“r”);

if (fs==NULL)

{

  printf(“\n File opening error.”);

  exit(1);

}

while((x=fgetc(fs))!=EOF)

{

  switch(x)

  {

    case ‘;’ :

    c++;

    break;

    case ‘{’ :

    sb++;

    break;

    case ‘(’ :

    b++;

    break;

    case ‘#’ :

    i++;

    break;

  }

}

fclose (fs);

printf(“\n Summary of ‘C’ Program\n”);

printf(“=========================”);

printf(“\n Total Statements : %d ”,c+i);

printf(“\n Include Statements : %d”,i);

printf(“\n Total Blocks {} : %d”,sb);

printf(“\n Total Brackets () : %d”,b);

printf(“\n==========================”);

}

OUTPUT:

Total Statements : 25

Include Statements : 4

Total Blocks {} : 5

Total Brackets () : 25

Explanation:

In the above program, the fgetc() function reads the file “prg2.c” character by character and returns the read character to variable ‘x’. The variable ‘x’ is passed then to switch case. Depending upon the contents of the variable ‘x’ respective counter is incremented in each case statement. Thus, at last all summary is printed.

 

6. fputc() :

This function writes the character to the file shown by the file pointer. It also increments the file pointer.

Syntax:

fputc(c,fp);

where fp is the file pointer and c is a variable written to the file pointed by file pointer.

14.12  Write a program to write text to a file using fputc() function.

 

# include <stdio.h>

# include <conio.h>

void main()

{

FILE *fp;

char c;

clrscr();

fp=fopen(“lines.txt”,“w”);

if(fp==NULL)

return;

else

{

  while( (c=getche())!=‘*’)

  fputc(c,fp);

}

fclose(fp);

}

OUTPUT:

India is my country *

Explanation:

In the above program, the text entered by the user is written into the file “lines.txt” using the fputc() function.

 

7. fgets() :

This function reads a string from a file pointed by file pointer. It also copies the string to a memory location referenced by an array.

14.13  Write a program to read text from the given file using fgets() function.

 

# include <stdio.h>

# include <conio.h>

void main()

{

FILE *fp;

char file[20],text[50];

int i=0;

printf(“Enter File Name :”);

scanf(“%s”,file);

fp=fopen(file,“r”);

if(fp==NULL)

{

  printf(“File not found\n”);

  return;

}

else

{

  if(fgets(text,50,fp)!=NULL)

  while(text[i]!=‘\0’)

  {

    putchar(text[i]);

    i++;

  }

}

}

OUTPUT:

Enter File Name : IO.C

# include <stdio.h>

Explanation:

In the above program, the function fgets() reads a string from the file pointed by file pointer. In this example, the IO.C file is opened and its first line is displayed on the screen.

 

8. fputs( ) :

This function is useful when we want to write a string into the opened file.

14.14  Make a program to write a string into a file using fputc() function.

 

# include <stdio.h>

# include <conio.h>

void main()

{

FILE *fp;

char file[12],text[50];

clrscr();

printf(“\n Enter the name of file :”);

scanf(“%s”, file);

fp=fopen(file,“w”);

if(fp==NULL)

{

  printf(“\nFile can not opened\n”);

  return;

}

else

{

  printf(“\n Enter Text Here : “);

  scanf(“%s”,text);

  fputs(text,fp);

}

fclose(fp);

}

OUTPUT:

Enter the name of file : data.dat

Enter Text Here : Good Morning

Explanation:

In the above example, “data.dat” file is opened in write mode. The text entered by the user is written in the file using the fputs() function. The user can read the contents of file from DOS prompt or one can read the contents of the file using the fgets() function as explained in the previous example.

 

9. putw() :

This function is used to write an integer value to file pointed by file pointer. This function deals with integer data only.

14.15  Write a program to enter integers and write them in the file using the putw() function.

 

# include <stdio.h>

# include <conio.h>

# include <process.h>

void main()

{

FILE *fp;

int v;

clrscr();

fp=fopen(“num.txt”,“w”);

if(fp==NULL)

{

  printf(“\n File dose not exist”);

  exit(1);

}

else

{

  printf(“\n Enter Numbers :”);

  while(1)

  {

    scanf(“%d”,&v);

    if(v==0)

    {

      fclose(fp);

      exit(1);

    }

    putw(v,fp);

  }

}

}

OUTPUT:

Enter Numbers : 1 2 3 4 5 0

Explanation:

In the above program, the file “num.txt” is opened in the write mode. Integers are then entered and written in the file using the putw() function. When the ‘0’ is entered, writing of data is stopped and file is closed.

 

10. getw ( ) :

This function returns the integer value from a file and increments the file pointer. This function deals with integer data only.

14.16  Write a program to read integers from the file using getw() function.

 

# include <stdio.h>

# include <conio.h>

# include <process.h>

void main()

{

FILE *fp;

int v;

clrscr();

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

if(fp==NULL)

{

  printf(“\n Entered numbers :”);

  exit(1);

}

else

{

  printf(“\n Entered numbers :”);

  while((v=getw(fp))!=EOF)

  printf(“%2d”,v);

  fclose(fp);

}

OUTPUT:

Entered numbers: 1 2 3 4 5

Explanation:

In the above program, the same file ‘num.txt’ used in the previous program is opened for reading the integers. Here, the function getw() reads integers from the file.

14.6  STRUCTURES READ AND WRITE

It is important to know how numerical data is stored on the disk by fprintf() function. Text and characters require one byte for storing them with fprintf(). Similarly for storing numbers in memory two bytes and for floats four bytes will be required.

All data types are treated as characters, for example the data 3456; it occupies two bytes in memory. But when it is transferred to the disk file using fprintf() function it would occupy four bytes. For each character one byte would be required. Even for float also each digit including dot (.) requires one byte. For example 12.34 would require five bytes. Thus, large amount of integers or float data requires large space on the disk. Hence, in the text mode storing of numerical data on the disk turns out to be inefficient. To overcome this problem the files should be read and written in binary mode, for which we use functions fread() and fwrite().

 

fwrite() & fread()

  1. fwrite(): This function is used for writing an entire structure block to a given file.
  2. fread(): This function is used for reading an entire block from a given file.

14.17  Write a program to write a block of structure elements to the given file using fwrite() function.

 

# include <stdio.h>

# include <conio.h>

# include <process.h>

void main()

{

struct

{

  char name[20];

  int age;

}

stud[5];

FILE *fp;

int i,j=0,n;

char str[15];

printf(“Enter the file name :”);

scanf(“%s”,str);

fp=fopen(str,”rb”);

if(fp==NULL)

{

  printf(“File dose not exist \n”);

  exit(1);

}

else

{

  printf(“How Many Records :”);

  scanf(“%d”,&n);

  for(i=0;i<n;i++)

  {

    printf(“Name :”);

    scanf(“%s”,&stud[i].name);

    printf(“Age :”);

    scanf(“%d”,&stud[i].age);

  }

  while(j<n)

  {

    fwrite(&stud,sizeof(stud),1,fp);

    j++;

  }

}

fclose(fp);

}

OUTPUT:

How Many Records :

2

Name :

SANTOSH

Age :

22

Name :

AMIT

Age :

14

Explanation:

In the above program, a file is opened in write mode. After successfully opening the file the number of records to be entered is asked. Using the for loop records are entered. Using the while loop and fwrite() statement within it records are written in the file.

14.18  Write a program to write and read the information about the player containing player’s name, age and runs. Use fread() and fwrite() functions.

 

# include <stdio.h>

# include <conio.h>

# include <process.h>

struct record

{

char player[20];

int age;

int runs;

};

void main()

{

FILE *fp;

struct record emp;

fp=fopen(“record.dat”,“w”);

if(fp==NULL)

{

  printf(“\n Cannot open the file”);

  exit(1);

}

clrscr();

printf(“\n Enter Player Name, Age & Runs Scored \n”);

printf(“ ==== ===== ==== === = ==== ======\n”);

scanf(“%s %d %d”,emp.player, &emp.age,&emp.runs);

fwrite(&emp,sizeof(emp),1,fp);

fclose(fp);

if((fp=fopen(“record.dat”, “r”))==NULL)

{

  printf(“\n Error in opening file”);

  exit(1);

}

printf(“\n Record Entered is \n”);

fread(&emp,sizeof(emp),1,fp);

printf(“\n%s %d %d”, emp.player, emp.age, emp.runs);

fclose(fp);

}

OUTPUT:

Enter Player Name, Age & Runs Scored

==== ===== ==== === = ==== ======

Sachin 25 10000

Record Entered is

Sachin 25 10000

Explanation:

In the above program, a user writes the information of the player using the fwrite function. The entire record of players which is containing information given in the structure is written first using the fwrite() function.

Similarly, the information written in the file can be read by using the fread() function. Thus, the program reads entire data file with single fread() and writes the data with single fwrite() function. These two functions are efficiently used for handling I/O files in comparison to fscanf() and fprintf().

14.19  Write a program to write a block of structure elements to the given file using fwrite() function. User should press ‘Y’ to continue and ‘N’ for termination.

 

# include <stdio.h>

# include <conio.h>

# include <process.h>

void main()

{

FILE *fp;

char next=‘Y’;

struct bike

{

  char name[40];

  int avg;

  float cost;

};

struct bike e;

fp=fopen(“bk.txt”,“wb”);

if(fp==NULL)

{

  puts(“Cannot open file”);

  exit(1);

}

clrscr();

while (next==‘Y’)

{

  printf(“\nModel Name, Average, Prize : ”);

  scanf(“%s %d %f”,e.name,&e.avg,&e.cost);

  fwrite(&e,sizeof(e),1,fp);

  printf(“\nAdd Another (Y/N :”);

  fflush(stdin);

  next=getche();

}

fclose(fp);

}

OUTPUT:

Model Name, Average, Prize : HONDA 80 45000

Add Another (Y/N : Y

Model Name, Average, Prize : SUZUKI 65 43000

Add Another (Y/N : Y

Model Name, Average, Prize : YAMAHA 55 48000

Add Another (Y/N : N

Explanation:

The above program is the same as the previous one. Here, the user has to press ‘Y’ to continue and ‘N’ to stop the program. After every key press of ‘Y’ a new record is added to the file.

14.20  Write a program to read the information about the bike like name, average and cost from the file using fread() function.

 

# include <stdio.h>

# include <conio.h>

# include <process.h>

void main()

{

FILE *fp;

struct bike

{

  char name[40];

  int avg;

  float cost;

};

struct bike e;

fp=fopen(“bk.txt”,“rb”);

if(fp==NULL)

{

  puts(“Cannot open file”);

  exit(1);

}

clrscr();

while(fread(&e,sizeof(e),1,fp)==1)

printf(“\n %s %d %.2f”,e.name,e.avg,e.cost);

fclose(fp);

}

OUTPUT:

Model Name, Average, Prize : HONDA 80 45000.00

Model Name, Average, Prize : SUZUKI 65 43000.00

Model Name, Average, Prize : YAMAHA 55 48000.00

Explanation:

In the above program, the records are written in the binary mode on the disk in the file “bk. txt”. Record writing will be over after the user presses ‘N’.

The same file is opened in read mode. The fread() function reads the records from the disk which is to be placed in the printf() statement to display on the screen. After the file detection of end of the file fread() function no more reads anything. It returns a ‘0’.

Functions fread() and fwrite() store the numbers more efficiently and the reading and writing of structures are easy.

14.7  OTHER FILE FUNCTION
  1. The fseek() function: The fseek() can be used to access the part of the file. The file pointer can be moved to any position in a file. It positions file pointer on the stream.

    The format of fseek() is as follows:

    fseek(filepointer,offset,position)

    Thus, three arguments are to be passed through this function. They are

    1. file pointer.
    2. Offset: offset may be positive (moving in forward from current position) or negative (moving backwards). The offset being a variable of type long.
    3. The current position of file pointer.

    Table 14.2 displays the various values of location of file pointer.

    Table 14.2 Locations of file pointer

    Integer Value

    Constant

    Location in the File

    0

    SEEK_SET

    Beginning of the file.

    1

    SEEK_CUR

    Current position of the file pointer.

    2

    SEEK_END

    End of the file

    Example:

    fseek(fp,10,0) or fseek(fp,10,SEEK_SET)

    The file pointer is repositioned in the forward direction by 10 bytes.

      14.21   Write a program to read the text file containing some sentence. Use fseek() and read the text after skipping n characters from beginning of the file.

     

    # include <stdio.h>

    # include <conio.h>

    void main()

    {

    FILE *fp;

    int n,ch;

    clrscr();

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

    printf(“\nContents of file\n”);

    while((ch=fgetc(fp))!=EOF)

    printf(“%c”,ch);

    printf(“\nHow many characters including spaces would you like to skip ? :”);

    scanf(“%d”,&n);

    fseek(fp,n,SEEK_SET);

    printf(“\n Information after %d bytes\n”,n);

    while((ch=fgetc(fp))!=EOF)

    printf(“%c”,ch);

    fclose(fp);

    }

    OUTPUT:

    Contents of file:

    THE C PROGRAMMING LANGUAGE INVENTED BY DENNIS RITICHE

    How many characters including spaces would you like to skip ? : 18

    Information after 15 bytes

    LANGUAGE INVENTED BY DENNIS RITICHE

    Explanation:

    In the above program, while statement is used for checking the end of the file. The file pointer is initially positioned at the beginning of the file and the whole text is printed.

    To reposition the file pointer the statement fseek() is used. The file pointer is to be positioned at nth character from the beginning of the file and the characters from nth position onwards will be printed on the screen.

    In the above program, one can use the statement fseek(fp,−n,SEEK_END) in place of fseek(fp,n,SEEK_SET) to read from backward direction from the end of the file.

      14.22   Write a program to read the last few characters of the file using the fseek() statement.

     

    # include <dos.h>

    # include <stdio.h>

    # include <conio.h>

    void main()

    {

    FILE *fp;

    int n,ch;

    clrscr();

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

    printf(“\nContents of file\n”);

    while((ch=fgetc(fp))!=EOF)

    printf(“%c”,ch);

    printf(“\n How many characters including spaces would you like to skip ? :”);

    scanf(“%d”,&n);

    fseek(fp,−n−2,SEEK_END);

    printf(“\nLast %d characters of a file\n”,−n−2);

    while((ch=fgetc(fp))!=EOF)

    printf(“%c”,ch);

    fclose(fp);

    }

    OUTPUT:

    How many characters including spaces would you like to skip? : 4

    Last 5 characters of a file

    WORLD

    Explanation:

    The statement fseek(fp,−n−2,SEEK_END); repositions the file pointer −n−2 bytes in the backward directions from the end of file. With this statement last characters of a statement can be printed on the screen, i.e. printing information will be from the position till the end of file. Here, the value of ‘n’ entered is 4. The value of –n−2 in this example works out to be –6. So the last six characters are displayed. The result shown here is ‘WORLD’ which contains five characters and the last is NULL. NULL is skipped.

      14.23   Write a program to display C program files in current directory. The user should select one of the files. Convert the file contents in capital and display the same on the screen. Also calculate total characters and lines.

     

    # include <ctype.h>

    # include <stdio.h>

    # include <conio.h>

    # include <process.h>

    void main()

    {

    FILE *fp;

    int l=0,c=0,ch;

    static char file [12];

    clrscr();

    system(“dir *.c/w”);

    printf(“\n Enter a file name :”);

    scanf(“%s”,file);

    fp=fopen(file,“r”);

    clrscr();

    printf(“\nContents of ‘c’ program File in capital case \n”);

    printf(“===============================================\n”);

    while((ch=fgetc(fp))!=EOF)

    {

      c++;

      if(ch==‘\n’)

      l++;

      printf(“%c”,toupper(ch));

    }

    printf(“\n Total Characters : %d”,c);

    printf(“\n Total Lines : %d”,l);

    }

    OUTPUT:

    Enter a file name : IO10.C

    Contents of ‘c’ program File in capital

    case main()

    {

    printf(“HELLO WORLD”);

    }

    Total Characters : 31

    Total Lines : 4

    Explanation:

    In the above program, system() statement is used for invoking MS-DOS command. The dir *.c/w displays the contents of the current directory. The function fgetc() reads the text of the entered file character by character till the end of the file. In the while loop, total characters and lines are counted. The line termination is to be identified by ‘\n’. Hence, the if statement is used for the identification of termination of line. In the same way, ‘\t’ can be used to take the account of tabs. The text is also converted to capital by using toupper() function and it is displayed.

  2. feof(): The macro feof() is used for detecting if the file pointer is at the end of file or not. It returns non-zero if the file pointer is at the end of file, otherwise it returns zero.

      14.24   Write a program to detect the end of file using the function feof(). Display the file pointer position for detecting end of file.

     

    # include <conio.h>

    # include <stdio.h>

    void main()

    {

    FILE *fp;

    char c;

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

    c=feof(fp);

    clrscr();

    printf(“File pointer at the beginning of the file : %d\n”,c);

    while(!feof(fp))

    {

      printf(“%c”,c);

      c=getc(fp);

    }

    c=feof(fp);

    printf(“File pointer at the end of file : %d ”,c);

    }

    File pointer at the beginning of the file : 0

    TECHNOCRATS LEAD THE WORLD

    File pointer at the end of file : 32

    Explanation:

    At starting, the feof() function returns 0 (zero) because the file pointer is at the beginning of file. After reading the contents of file the file pointer reaches at the end of file. At this stage, the feof() function returns non-zero value which is 32 in this program.

    14.8  SEARCHING ERRORS IN READING/WRITING FILES

    While performing read or write operation a few times, we do not get results successfully. The reason may be that the attempt of reading or writing operation may not be correct. The provision must be provided for searching the error while read/write operations are carried out.

    The C language provides standard library function ferror(). This function is used for detecting any error that might occur during read/write operation of a file. It returns a ‘0’ while the attempt is successful otherwise non-zero in case of failure.

  3. ferror(): The ferror() is used to find out error when file read write operation is carried out.

      14.25   Write a program to detect an error with read/write operation of a file.

     

    # include <stdio.h>

    # include <conio.h>

    # include <process.h>

    void main()

    {

    FILE *fp;

    char next=‘Y’;

    char name[25];

    int marks;

    float p;

    fp=fopen(“marks.dat”,“r”);

    if(fp==NULL)

    {

      puts(“Can not open file”);

      exit(1);

    }

    clrscr();

    while(next==‘Y’)

    {

      printf(“\n Enter Name, Marks, Percentage”);

      scanf(“%s %d %f”,name,&marks,&p);

      p=marks/7;

      fprintf(fp,“%s %d %f”,name,&marks,&p);

      if(ferror(fp))

      {

        printf(“\n Unable to write data ? ”);

        printf(“\n File opening mode is incorrect.”);

        fclose(fp);

        exit(1);

      }

      printf(“Continue(Y/N”);

      fflush(stdin);

      next=getche();

    }

    fclose(fp);

    }

    OUTPUT:

    Enter Name, Marks

    KAMAL 540

    Unable to write data?

    File opening mode is incorrect.

    Explanation:

    In the above program, the fprintf() function fails to write the entered data to the file because it is opened in the read mode. Hence, write operation cannot be done. The error generated is caught by the ferror() function and the program terminates.

      14.26   Write a program to catch the error that occurs while read operation of a file using ferror() function.

     

    # include <stdio.h>

    # include <process.h>

    # include <conio.h>

    void main()

    {

    FILE *f;

    char c;

    clrscr();

    f=fopen(“io8.c”,“w”);

    if(f==NULL)

    {

      printf(“\nCannot open file”);

      exit(1);

    }

    while((c=fgetc(f))!=EOF)

    {

      if(ferror(f))

      {

        printf(“\nCan’t read file.”);

        fclose(f);

        exit(1);

      }

      printf(“%c”,c);

      getch();

    }

    fclose(f);

    }

    OUTPUT:

    Can’t read file.

    Explanation:

    In the above program, the file ‘io8.c’ is opened in write mode. Whereas the function fgetc() would certainly fail because it used for reading operation the fgetc() is trying to read the file which is impossible. This never happens because the file that is opened in write mode cannot be read and vice versa.

  4. perror(): It is a standard library function which prints the error messages specified by the compiler. A program is illustrated below for understanding.

      14.27   Write a program to detect and print the error message using perror() function.

     

    # include <stdio.h>

    # include <conio.h>

    # include <process.h>

    void main()

    {

    FILE *fr;

    char c,file[]=“lines.txt”;

    fr=fopen(file,“w”);

    clrscr();

    while(!feof(fr))

    {

      c=fgetc(fr);

      if(ferror(fr))

      {

        perror(file);

        exit(1);

      }

      else

      printf(“%c”,c);

    }

    fclose(fr);

    }

    OUTPUT:

    lines.txt : Permission Denied

    Explanation:

    In the above program to print the error message a user can use perror() function instead of printf(). The output of the above program is ‘lines.txt: Permission Denied’. We can also specify our own message together with the system error message. In the above example, ‘file’ variable prints the file name ‘lines.txt’ together with compiler’s message ‘Permission Denied’.

  5. ftell():It is a file function. It returns the current position of the file pointer. It returns the pointer from the beginning of file. The current position of the file is detected with this function.

      14.28   Write a program to print the current position of the file pointer in the file using the ftell() function.

     

    # include <stdio.h>

    # include <conio.h>

    void main()

    {

    FILE *fp;

    char ch;

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

    fseek(fp,21,SEEK_SET);

    ch=fgetc(fp);

    clrscr();

    while(!feof(fp))

    {

      printf(“%c\t”,ch);

      printf(“%d\n”,ftell(fp));

      ch=fgetc(fp);

    }

    fclose(fp);

    }

    OUTPUT:

    W 22

    O 23

    R 24

    L 25

    D 26

      28

    Explanation:

    In the above program, fseek() function sets the cursor position on byte 21. The fgetc() function in the while loop reads the character after 21st character. The ftell() function prints the current pointer position in the file. When feof() function is found at the end of file, program terminates.

  6. rewind(): This function resets the file pointer at the beginning of the file.

      14.29   Write a program to show how rewind() function works.

     

    # include <stdio.h>

    # include <conio.h>

    void main()

    {

    FILE *fp;

    char c;

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

    clrscr();

    fseek(fp,12,SEEK_SET);

    printf(“Pointer is at %d\n”, ftell(fp));

    printf(“Before rewind() : ”);

    while(!feof(fp))

    {

      c=fgetc(fp);

      printf(“%c”,c);

    }

    printf(“\bAfter rewind() : ”);

    rewind(fp);

    while(!feof(fp))

    {

      c=fgetc(fp);

      printf(“%c”,c);

    }

    }

    OUTPUT:

    Pointer is at 12

    Before rewind() : LEAD THE WORLD

    After rewind() : TECHNOCRATS LEAD THE WORLD

    Explanation:

    In the above program, the fseek() function sets the pointer position on the 12th character. The first while loop reads and prints the file from the current position up to the end in which first 12 characters of file are not displayed. Before starting of the second while loop the rewind() function sets the pointer position at the beginning of file, i.e. on 1 character. The while loop reads all the characters of the file from starting to end. In short the rewind() function sets the file pointer at the beginning of the file.

  7. unlink() or remove(): These functions delete the given file in the directory. It is similar to the del command in DOS.

      14.30   Write a program to delete the given file from the disk using remove() or unlink() function.

     

    # include <dos.h>

    # include <stdio.h>

    # include <conio.h>

    # include <process.h>

    void main()

    {

    FILE *fp;

    char file[15];

    clrscr();

    system(“dir *.txt”);

    printf(“ Enter The File Name :”);

    scanf(“%s”,file);

    fp=fopen(file,“r”);

    if(fp==NULL)

    {

      printf(“\nFile dose not exist”);

      exit(1);

    }

    else

    {

      remove(file);

      printf(“\n File (%s) has been deleted !”,file);

    }

    }

    OUTPUT:

    Enter The File Name : TEXT.TXT

    File (TEXT.TXT) has been deleted !

    Explanation:

    In the above program, file to be deleted is entered. The entered file is opened in read mode. If the fopen() fails to open the file then it returns NULL to pointer *fp, i.e. file does not exist and program terminates. By using unlink() or remove() function the entered file is deleted.

  8. rename(): This function changes name of the given file. It is similar to the DOS command rename.

      14.31   Write a program to change the name of the file. Use rename() function.

     

    # include <stdio.h>

    # include <conio.h>

    void main()

    {

    char old[12], new[12];

    system(“dir *.c /w”);

    printf(“\nOld File Name : ”);

    scanf(“%s”,old);

    printf(“New File Name : ”);

    scanf(“%s”,new);

    rename(old,new);

    system(“dir *.c/w”);

    }

    OUTPUT:

    Old File Name : old.c

    New File Name : new.c

    Explanation:

    In the above program, the rename() function changes the name of the given file with a new name. Its meaning is similar to DOS command ‘rename’.

      14.32   Write a program to copy the contents of one file to another file.

     

    /* File copy program */

    # include <stdio.h>

    # include “process.h”

    void main()

    {

    /* Declaration */

    FILE *ft,*fs;

    int c=0;

    clrscr();

    /* Opening Files */

    fs=fopen(“a.txt”,“r”);

    ft=fopen(“b.txt”,“w”);

    if(fs==NULL )

    {

      printf(“\n Source file opening error.”);

      exit(1);

    }

    else

    if(ft==NULL)

    {

      printf(“\n Target file opening error.”);

      exit(1);

    }

    /* Reading file */

    while(!feof(fs))

    {

      fputc(fgetc(fs),ft);

      c++;

    }

    printf(“\n %d Bytes copied from ‘a.txt’ to ‘b.txt.’”,c);

    /* Closing Files */

    c=fcloseall();

    printf(“\n %d files closed.”,c);

    }

    OUTPUT:

    45 Bytes copied from ‘a.txt’ to ‘b.txt.

    2 files closed.

    Explanation:

    In the above program, two files are opened. The source file ‘a.txt’ is opened in read mode and the target file ‘b.txt’ is opened in the write mode. With the fputc() function the contents read by fgetc() is written to the target file. To count the number of characters of source file ‘c’ counter is used. The fcloseall() function closes all the opened files and returns the number of files closed. This return value of fcloseall() is collected by the variable ‘c’.

      14.33   Read the contents of three files and find the largest file.

     

    # include <stdio.h>

    # include <conio.h>

    # include <alloc.h>

    # include <process.h>

    void main()

    {

    FILE *f[3],*fp;

    int x[3],l,y=0,k=0,t=0;

    char c1;

    char name[3][11]={“1.txt”,“2.txt”,“3.txt”};

    clrscr();

    for(l=0;l<3;l++)

    {

      fp=fopen(name[l],“r”);

      f[l]=fp;

      if(fp==NULL)

      {

        printf(“\n %s file not found. ”,name[l]);

        exit(1);

      }

    }

    clrscr();

    for(l=0;l<3;l++)

    {

      while(!feof(f[l]))

      {

        c1=fgetc(f[l]);

        x[l]=y++;

      }

      y=0;

    }

    clrscr();

    fcloseall();

    for(l=0;l<=2;l++)

    {

      printf(“File : %s Bytes : %d\n”,name[l],x[l]);

      t=t+x[l];

    }

    for(l=t;l>=1;l−−)

    {

      for(k=0;k<3;k++)

      {

        if(l==x[k])

        {

          printf(“%s are the largest file.”,name[k]);

          exit(1);

        }

      }

    }

    }

    OUTPUT:

    File : 1.txt Bytes : 16

    File : 2.txt Bytes : 20

    File : 3.txt Bytes : 25

    3.txt are the largest file.

    Explanation:

    In the above program, an array of file pointer and a separate file pointer fp are declared. The two-dimensional character array is used for storing file names. Using file pointer array in the for loop, three files are opened in read mode. Each element of file pointer array points to the corresponding elements of character array i.e. file names.

    The fgetc() function in the while loop reads contents of each file one by one. The numbers of characters are also written to integer array in the same loop. At the end, the values stored in integer array are compared with one another and the file containing the largest number of bytes is detected. The name of the largest file is displayed.

      14.34   Write a program to copy up to 100 characters from a file to an array. Then copy the contents of an array to another file.

     

    # include <stdio.h>

    # include <conio.h>

    # include <process.h>

    # define SIZE 100

    void main()

    {

    FILE *f,*f2;

    static char c,ch[SIZE];

    int s=0,x=0;

    clrscr();

    f=fopen(“poem.txt”,“r”);

    f2=fopen(“alpha.txt”, “w”);

    if(f==NULL || f2==NULL )

    {

      perror(“?”);

      exit(1);

    }

    clrscr();

    while(!feof(f))

    {

      c=fgetc(f);

      x++;

      if(x==99)

      {

        fcloseall();

        exit(1);

      }

      else

      ch[s++]=c;

    }

    fclose(f);

    for(s=0;s<=100;s++)

    fputc(ch[s],f2);

    fclose(f2);

    perror(“Process Completed”);

    }

    OUTPUT:

    Process Completed : Error 0

    Explanation:

    In the above program, the contents of file ‘poem.txt’ are read using and copied to a character array ch[]. The same array is read and written to the file ‘alpha.txt’ using the fputc() function.

      14.35   Write a program to copy the contents of one file to another three files. Display the contents of the three files.

     

    # include <stdio.h>

    # include <conio.h>

    # include “process.h”

    void main()

    {

    FILE *ft,*fs,*fa,*fb;

    int c=0;

    char k;

    clrscr();

    fs=fopen(“intl.txt”,“r”);

    ft=fopen (“a.txt”,“w”);

    fa=fopen(“b.txt”,“w”);

    fb=fopen(“c.txt”,“w”);

    if(fs==NULL )

    {

      printf(“\n Source file opening error.”);

      exit(1);

    }

    else

    if(ft==NULL || fa==NULL || fb==NULL )

    {

      printf(“\n Target file opening error.”);

      exit(1);

    }

    while(!feof(fs))

    {

      k=fgetc(fs);

      if(c<100)

      fputc(k,ft);

      if(c>=100 && c<200)

      fputc(k,fa);

      if(c<200 && c<=282)

      fputc(k,fb);

      c++;

      if(c==283) break;

    }

    fcloseall();

    ft=fopen(“a.txt”,“r”);

    fa=fopen(“b.txt”,“r”);

    fb=fopen(“c.txt”,“r”);

    if(ft==NULL || fa==NULL || fb==NULL )

    {

      printf(“\n Target file opening error.”);

      exit(1);

    }

    while(!feof(ft))

    {

      k=fgetc(ft);

      printf(“%c”,k);

    }

    while(!feof(fa))

    {

      k=fgetc(fa);

      printf(“%c”,k);

    }

    while(!feof(fb))

    {

      k=fgetc(fb);

      printf(“%c”,k);

    }

    fcloseall();

    }

    OUTPUT:

    -----------------------------------------------------------------------

    Microsoft Windows 98 Seco_nd Edition
    README for Pan-European Regional Settings
    (c) Copyright Micro_oft Corporation, 1999

    -----------------------------------------------------------------------

    Explanation:

    In this program, the text file intl.txt is opened in the read mode. Another three files a.txt, b.txt and c.txt are opened in the write mode. Total 300 characters are read from the file and 100 characters are written into each file. Later contents of these a.txt, b.txt and c.txt are displayed on the screen.

14.9  LOW-LEVEL DISK I/O

Text files can be copied from one file to other or in many files. However if we attempt to open binary files such as .EXE in text mode, unexpectedly the process of getting characters would stop. This is because whenever ASCII value 26 is observed copying work stops due to EOF(). Another approach to copy such binary files are with low-level disk I/O.

In the low-level disk I/O disk operation, data cannot be written as character-by-character or with sequence of characters as it carried in the high-level disk I/O functions. In the low-level disk I/O functions, buffers are used to carry the read and write operations.

Buffer plays an important role in the low-level disk I/O program. The programmer needs to declare the appropriate buffer size. The low-level disk I/O operations are more efficient and quick than the high-level disk I/O operations.

  1. Opening a file: To open a file or files open() function is used. This function is defined in ‘io.h’. The syntax of open() is as given below.

    Syntax:

    int open(const char *f_name, int access, unsigned mode)

    In the low-level operation, a number is assigned to the file and the number is used to refer the file. If open() returns –1, it means that the file could not be opened otherwise the file is successfully opened.

    Table 14.3 describes the file-opening modes in the low-level disk I/O operations.

    Table 14.3 File-opening modes

    Mode

    Meaning

    O_APPEND

    Opens a file in append mode.

    O_WRONLY

    Creates a file for writing only.

    O_RDONLY

    Opens a file for writing only.

    O_RDWR

    Opens a file for read/write operations.

    O_BINARY

    Opens a file in binary mode.

    O_CREATE

    Opens a new file for writing.

    O_EXCEL

    When used with O_CREATE, if a file exists it is not overwritten.

    O_TEXT

    Creates a text file.

    When O_CREATE flag is used, it also requires one of arguments described in Table 14.4 to verify the read/write status of the file. These arguments are called permission argument. The programmer need to include the header file ‘stat.h’ and ‘types.h’ along with ‘fcntl.h’.

    Table 14.4 Permission argument

    S_IWRITE

    Writing to the file allowed

    S_IREAD

    Reading from the file allowed

  2. Writing a file: The write() function is used to write() data into the file. This function is defined in ‘io.h’. The syntax of write() function is as given below.

    Syntax:

    int write(int handle, void *buf, unsigned nbyte);

    Returns the number of bytes written or –1 if an error occurs.

  3. Reading a file: The read() function reads a file. The syntax of read() function is as follows.

    Syntax:

    int read(int handle, void *buf, unsigned len);

    Upon successful end, it returns an integer specifying the number of bytes placed in the buffer; if the file was opened in text mode, read does not count carriage returns or ctrl-Z characters in the number of bytes read. On error, it returns –1 and sets errno.

  4. Closing a file: The close() function closes the file. This function is defined in ‘io.h’.The syntax of close() is as per given below.

    Syntax:

    int _close(int handle);

    int close(int handle);

    Upon successful finish, close & _close returns 0; otherwise, they return –1 and set errno.

      14.36   Write a program to enter text through keyboard and store it on the disk. Use low-level disk I/O operations.

     

    # include <stdio.h>

    # include <conio.h>

    # include <io.h>

    # include <fcntl.h>

    void main()

    {

    char file[10];

    char buff[15];

    int s,c;

    puts(“\n Enter a file name :”);

    gets(file);

    s=open(file,O_CREAT | O_TEXT);

    if(s==−1)

    puts(“\n File does not exits”);

    else

    {

      puts( “Enter text below : ”);

      for(c=0;c<=13;c++)

      buff[c]=getche();

      buff[c]=’\0’;

      write(s,buff,15);

      close(s);

    }

    }

    OUTPUT:

    Enter a file name : TEXT.txt

    Enter text below : PROGRAMMING IN C

    Explanation:

    In the above program, a prompt appears for asking a file name to be created. A file is created with the name entered by the user. If the file is already present, it would not be over-written and the entered text would not be written in the file. If open() fails to open the file then it will return –1 and this value is assigned to variable s. The if statement checks the value of s and respective blocks are executed. In the else block, the getche() within the for loop reads 14 characters through the keyboard and after the for loop the string is terminated by the NULL character. Here, instead of using gets(), getche() is used. In gets(), there may be a possibility that the entered text may be of less than 15 characters. In such a case, some garbage values are also written in the file. To avoid the garbage we used getche() within the for loop to exactly read character equal to that mentioned in the write() statement, i.e. 15.

      14.37   Write a program to read text from a specified file from the disk. Use low-level disk I/O operations.

     

    # include <stdio.h>

    # include <conio.h>

    # include <io.h>

    # include <fcntl.h>

    # include <process.h>

    void main()

    {

    char file[10],ch;

    int s;

    clrscr();

    puts(“\n Enter a file name :”);

    gets(file);

    s=open(file,O_RDONLY);

    if (s==−1)

    {

      puts(“\n File does not exits.”);

      exit(1);

    }

    else

    {

      while(!eof(s))

      {

        read(s,&ch,1);

        putch(ch);

      }

    close(s);

    }

    }

    OUTPUT:

    Enter a file name : TEXT.txt

    PROGRAMMING IN C

    Explanation:

    In the above program, the file is opened in read-only mode. The read() declaration within the while loop reads single character from the file destined by the file handler s. The putch() statement following the read() declaration shows the read character on the console. The while loop ends when the end of file is detected.

  5. Setting Buffer: The size of buffer can be set using the setbuf() function. This function is defined in ‘stdio.h’. The syntax of setbuf() is as follows.

    Syntax:

    void setbuf( FILE *fp, char *buffer);

      14.38 Write a program to set a buffer size using setbuf() function.

     

    # include <stdio.h>

    # include <conio.h>

    void main()

    {

    char buff[22];

    clrscr();

    setbuf(stdout,buff);

    printf (“\nThis book teaches C”);

    fflush(stdout);

    }

    OUTPUT:

    This book teaches C

    Explanation:

    In the above program, a character array buff[22] is declared. The setbuf() function sets the buffer size as per the size of buff[22] array. The printf() statement displays the message written in it. If the characters written in the printf() statement are more than the buffer size i.e. 22 the program will be terminated with a critical error. Hence, the text that is to be displayed using any output function should be less or equal to the size of buffer.

14.10  COMMAND LINE ARGUMENTS

An executable program that performs a specific task for operating system is called a command. The commands are issued from the prompt of operating system. Some arguments are to be associated with the commands hence these arguments are called command line arguments. These associated arguments are passed to the program.

In C language, every program starts with a main() function and it marks the beginning of the program. We have not provided any arguments so far in the main() function. Here, we can make arguments in the main like other functions. The main() function can receive two arguments and they are: (1) argc and (2) argv. The information contained in the command line is passed on to the program through these arguments when the man() is called up by the system.

  1. Argument argc: An argument argc counts the total number of arguments passed from command prompt. It returns a value which is equal to the total number of arguments passed through the main().
  2. Argument argv: It is a pointer to an array of character strings which contain names of arguments. Each word is an argument.

Example:

Copy file1 file2

Here, file1 and file2 are arguments and copy is a command. The first argument is always an executable program followed by associated arguments. If you do not specify the argument, the first program name itself is an argument but the program will not run properly and will flag an error.

A program on above concept is explained below.

  14.39 Write a program to display the number of arguments and their names.

 

# include <stdio.h>

# include <conio.h>

main(int argc, char *argv[])

{

int x;

clrscr();

printf(“\n Total number of arguments are %d \n”,argc);

for(x=0;x<argc;x++)

printf(“%s\t”,argv[x]);

getch();

return 0;

}

OUTPUT:

Total number of arguments are 4

C:\TC\C.EXE A B C

Explanation:

To execute this program, one should create its executable file and run it from the command prompt with required arguments. The above program is executed using the following steps:

  1. Compile the program.
  2. Make its exe file (executable file).
  3. Switch to the command prompt. (C:\TC>)
  4. Make sure that the exe file is available in the current directory.
  5. Type the following bold line.

C:\TC> C.EXE HELP ME

In the above example, c.exe is an executable file and ‘HELP ME’ are taken as arguments. The total numbers of arguments including program file name are three.

14.11  APPLICATION OF COMMAND LINE ARGUMENTS

Below given programs can be used on command prompt similar to that of DOS commands.

  1. TYPE:

      14.40 Write a program to read any file from command prompt. Use command line arguments. (Save this program as read.c)

     

    # include <stdio.h>

    # include <conio.h>

    # include <process.h>

    main( int argc, char *argv[])

    {

    FILE *fp;

    int ch;

    fp=fopen(argv[1],”r”);

    if(fp==NULL)

    {

      printf(“Can not open file”);

      exit(0);

    }

    while(!feof(fp))

    {

      ch=fgetc(fp);

      printf(“%c”,ch);

    }

    fclose(fp);

    return 0;

    }

    Explanation:

    The above program after getting its exe file will run similarly as type command of DOS. On the command prompt, one should write first exe file name and file name to be read. The contents of file will be displayed on the screen.

  2. DEL:

      14.41 Write a program using command line argument to perform the task of DEL command of DOS. (Save this program as cut.c)

     

    # include <stdio.h>

    # include <conio.h>

    # include <process.h>

    main(int argc, char *argv[])

    {

    FILE *fp;

    if(argc<2)

    {

      printf(“Insufficient Arguments”);

      exit(1);

    }

    fp=fopen(argv[1],“r”);

    if(fp==NULL)

    {

      printf(“File Not Found”);

      exit(1);

    }

    unlink(argv[1]);

    printf(“File has been deleted ”);

    return 0;

    }

    Explanation:

    This program performs the task of DEL command of disk operating system. It deletes only one file at a time. It also creates exe file of this program and executes it on the command prompt. User should give the file name for deleting. Opening it in read mode checks the existence of file. The file will be deleted in case it exists. In the program, appropriate messages are displayed if user makes any mistake. Error messages are ‘insufficient arguments’, ‘file not found’ and “file has been deleted”.

  3. RENAME:

      14.42 Write a program using command line argument to perform the task of REN command of DOS. (Save this program as change.c)

     

    # include <stdio.h>

    # include <conio.h>

    # include <process.h>

    main(int argc, char *argv[])

    {

    FILE *fp,*sp;

    if(argc<3)

    {

      printf(“Insufficient Arguments”);

      exit(1);

    }

    fp=fopen(argv[1],“r”);

    if(fp==NULL)

    {

      printf(“File Not Found”);

      exit(1);

    }

    sp=fopen(argv[2],“r”);

    if(sp==NULL)

    {

      fcloseall();

      rename(argv[1],argv[2]);

    }

    else

    printf(“Duplicate file name or file is in use.” );

    return0;

    }

    Explanation:

    In the above program, the main() receives two file names. The existence of old file is checked through read mode. If the file does not exist, program terminates. On the other hand, if the second file exists the rename operation can not be done. If the file pointer of the second file contains the NULL value, then only rename operation is performed otherwise program terminates with an appropriate error message.

14.12  ENVIRONMENT VARIABLES

Environment variables provide different system settings/path related to operating system. These variables are available in both MS-DOS and UNIX operating system. The output depends upon the operating system. The following program displays the output related to MS-DOS.

  14.43 Write a program to use the environment variable and display various settings.

 

# include <stdio.h>

# include <conio.h>

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

{

int i;

clrscr();

for(i=0;env[i]!=NULL;++i)

{

  printf(“%s\n”,env[i]);

}

}

OUTPUT:

TMP=C:\WINDOWS\TEMP

TEMP=C:\WINDOWS\TEMP

PROMPT=$p$g

winbootdir=C:\WINDOWS

COMSPEC=C:\WINDOWS\COMMAND.COM

PATH=C:\WINDOWS;C:\WINDOWS\COMMAND;C:\JDK1.2.1\BIN;C:\JDK1.2.1;

CMDLINE=WIN

windir=C:\WINDOWS

14.13  I/O Redirection

Normally a program receives the input from keyboard, and on processing the input result is provided on the output device such as monitor. Using MSDOS, the feature redirection permits to send the result to disk instead of the monitor. It is also possible to bring information in program from disk instead of the keyboard.

Consider the DOS command dir > abc; execute it at the DOS prompt. Here, dir is the internal DOS command and abc is the name of the file. Here, the list of files and directories, instead of displaying on the screen, is redirected in a text file abc i.e. the files and directories would, possible to be seen in abc file. For this use, type abc command at DOS prompt.

From the above example, the reader can understand that the output of the command can be redirected to another file. Using redirection the output of the program instead of displaying on the screen is stored on the disk in the form of a file. With this, we can avoid creating a separate function for writing files to the disk or to the printer. Thus, this is an advantage and a convenient approach for writing files to the disk. Using this redirection concept both read and write operations are possible.

The following steps can be adopted to follow the concept of redirection:

  1. Compile a program
  2. Get an executable file .exe
  3. Execute this .exe file on the DOS prompt with redirection
    Example: read.exe > input.txt
  4. Input the data from keyboard
  5. See the typed data on DOS prompt by typing Type input.txt

Executing the following programs can follow the concept of redirection.

  14.44 Write a program to read a character from the keyboard till the user presses enter.

 

# include <stdio.h>

# include <conio.h>

void main()

{

char c;

while((c=getc(stdin))!=‘\n’)

putc(c,stdout);

}

OUTPUT:

1 2 3 4 5 6 7 8 9

Explanation:

On compiling this program, we would get an executable file read.exe. Execute this program on the DOS prompt as given below.

C> read.exe > input.txt

Now, whatever data is inputted, it is redirected to text file input.txt. To confirm, type the file using type command. The output would be

1 2 3 4 5 6 7 8 9

The redirection operator ‘>’ transfers any output proposed for screen to the file followed by the operator.

It is optional to input data in the program. We can also redirect output of the program generated by itself to the text file. The above program illustrates this point.

  14.45 Write a program to display A to Z characters.

 

# include <stdio.h>

# include <conio.h>

void main()

{

int a;

clrscr();

for(a=65;a<91;a++)

printf(“\t%c\t”,a);

printf(“\n”);

}

OUTPUT:

A    B    C    D    E

F    G    H    I    J

K    L    M    N    O

P    Q    R    S    T

U    V    W    X    Y

Z

Explanation:

After compilation we get the exe file. Execute it at DOS prompt as given below.

c> alpha.exe > abc.txt

After execution, the output generated by the program is directed to file abc.txt. It is also possible to send the output to printer. For this, follow the following syntax:

c> alpha.exe > prn

We can also redirect the input to the program from a file. Instead of writing with the keyboard, a complete file can be transferred. The below given program explains this point.

C> read.exe < abc.txt

This command display output is

 

A    B    C    D    E

F    G    H    I    J

K    L    M    N    O

P    Q    R    S    T

U    V    W    X    Y

Z

Here, the contents of abc.txt are redirected to program read.exe. The user need not enter any data through the keyboard. The entire contents of abc.txt are used as input and the same is displayed. Here, the ‘<’ redirection operator is used.

Input and output can be redirected simultaneously. Here, input is taken from a file and transferred to another file. The program acts as mediator between both the files. The following command illustrates this process:

C> read.exe < abc.txt > alpha.txt

In this process, program reads redirected data from the file abc.txt. Also instead of displaying output on the screen, it would be redirected to the file alpha.txt. The contents of both the files abc.txt and alpha.txt will be the same. User can confirm by typing them.

SUMMARY

This chapter explains the procedure for opening files and storing information in them. The various I/O functions related to high level and low-level file disk operations are elaborated with programming examples. After having gone through structures read and write, you are now familiar with fwrite() and fread() functions. Using other file functions, we described functions related to seeking the particular record, end of file and detecting the errors. Command line arguments to accept arguments from command prompt of the operating system are described. Simulations of various DOS commands with examples are also narrated. Reader is also made familiar with I/O-REDIRECTIONS in which output of the program can be redirected to file or printer. Also, data from file can also be redirected to program.

EXERCISES

I  True or false:

  1. A file is a set of records.
  2. The FILE pointer contains all information about a file.
  3. Without the file pointer file can be operated in C.
  4. In sequential file data can be read directly.
  5. In random file the last record can be read first.
  6. The fopen() is used to open file.
  7. The statement FILE *p declares file pointer.
  8. The ‘r‘ mode means file is opened for writing only.
  9. The ‘w‘ mode opens a new file on the disk.
  10. The function fputc() writes data to the file.
  11. The fprintf() is similar to printf().
  12. The function feof() finds the end of file.
  13. The getw() is not associated with any file operation.
  14. The SEEK_CUR indicates current position of the file pointer.
  15. The ferror() reports error occurred during file read/write operation.
  16. The function rewind() reverses the contents of a file.
  17. The ‘wb’ creates a file in binary mode.
  18. The O_APPEND is a low-level disk operation.
  19. The argc and argv are not command line arguments.

II  Match the following correct pairs given in Group A with Group B:

  1.  

  2.  

III  Select the appropriate option from the multiple choices given below:

  1. The fscanf() statements reads data from
    1. file
    2. keyboard
    3. Both (a) and (b)
    4. None of the above
  2. When fopen() fails to open a file it returns
    1. NULL
    2. −1
    3. 1
    4. None of the above
  3. A file opened in w+ mode can be
    1. read/write
    2. only read
    3. only write
    4. None of the above
  4. Command line arguments are used to accept argument from
    1. command prompt of operating system
    2. through scanf() statement
    3. Both (a) and (b)
    4. None of the above
  5. The redirection operator ‘>’ transfers any output to
    1. text file
    2. console
    3. both (a) and (b)
    4. None of the above
  6. This function is used to detect the end of file
    1. feof()
    2. ferror()
    3. fputs()
    4. fgetch()
  7. The EOF is equivalent to
    1. −1
    2. 0
    3. 1
    4. None of the above

IV  Attempt the following programming exercises:

  1. Write a program to generate a data file containing the list of cricket players, no. of innings played, highest run score and no. of hatriks made by them. Use structure variable to store the cricketer’s name, no. of innings played, highest run score and the number of hatricks.
  2. Write a program to reposition the file to its 10th character.
  3. Write a program to display contents of file on the screen. The program should ask for file name. Display the contents in capital case.
  4. Write a program to find the size of the file.
  5. Write a program to combine contents of two files in a third file. Add line number at the beginning of each line.
  6. Write a program to display numbers from 1 to 100. Redirect the output of the program to text file.
  7. Write a program to write contents of one file in reverse into another file.
  8. Write a program to interchange contents of two files.

V  Answer the following questions:

  1. What is the difference between end of a file and end of a string?
  2. Distinguish between text mode and binary mode operation of a file.
  3. What is the use of fseek()? Explain its syntax.
  4. Distinguish between the following functions:
    1. scanf() and fscanf()
    2. getc() and getchar()
    3. putc() and fputc()
    4. putw() and getw()
    5. ferror() and perror()
    6. feof() and eof()
  5. How does an append mode differs from a write mode?
  6. Why the header file stdio.h is frequently used in C Language?
  7. Compare between printf and fprintf functions.
  8. Distinguish between the following modes:
    1. w and w+
    2. r and r+
    3. rb and rb+
    4. a and a+
  9. Explain low-level disk operations.
  10. Explain command line arguments.
  11. Explain environment variables.
  12. How redirection of input and output is done? Explain in brief.

VI  What will be the output/s of the following program/s?

  1.  

    # include <process.h>

    void main()

    {

    FILE *fp;

    char c;

    clrscr();

    printf(“Contents of file before appending :\n”);

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

    while(!feof(fp))

    {

      c=fgetc(fp);

      printf(“%c”,c);

    }

    fp=fopen (“data.txt”,“a”);

    if(fp==NULL)

    {

      printf(“File can not appended”);

      exit(1);

    }

    printf(“\n Enter string to append :”);

    while(c!=‘.’)

    {

      c=getche();

      fputc(c,fp);

    }

    fclose(fp);

    printf(“\n Contents of file After appending :\n”);

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

    while(!feof(fp))

    {

      c=fgetc(fp);

      printf(“%c”,c);

    }

    }

  2.  

    # include <process.h>

    void main()

    {

    FILE *fp;

    Char c=‘ ’;

    Clrscr();

    Fp=fopen(“data.txt”,“w+”);

    if(fp==NULL)

    {

      printf(“Can not open file”);

      exit(1);

    }

    printf(“Write data & to stop press ‘.’ :”);

    while(c!=‘.’)

    {

      c=getche();

      fputc(c,fp);

    }

    rewind(fp);

    printf(“\n Contents read :”);

    while(!feof(fp))

    printf(“%c”,getc(fp));

    }

  3.  

    # include <process.h>

    void main()

    {

    FILE *fp;

    char c=‘ ’;

    clrscr();

    fp=fopen(“data.txt”,“a+”);

    if(fp==NULL)

    {

      printf(“Cannot open file”);

      exit(1);

    }

    printf(“Write data & to stop press ‘.’ :”);

    while(c!=‘.’)

    {

      c=getche();

      fputc(c,fp);

    }

    printf(“\n Contents read :”);

    rewind(fp);

    while(!feof(fp))

    printf(“%c”,getc(fp));

    }

  4.  

    # include <process.h>

    void main()

    {

    FILE *fp;

    char c=‘ ’

    clrscr();

    fp=fopen(“data.dat”,“wb”);

    if(fp==NULL)

    {

      printf(“Cannot open file”);

      exit(1);

    }

    printf(“Write data & to stop press ‘.’ :”);

    while(c!=‘.’)

    {

      c=getche();

      fputc(c,fp);

    }

    fclose(fp);

    fp=fopen(“data.dat”,“rb”);

    printf(“\n Contents read :”);

    while(!feof(fp))

    printf(“%c”,getc(fp));

    }

  5.  

    void main()

    {

    FILE *fp;

    char c;

    clrscr();

    fp=fopen(“lines.txt”,“w”);

    if(fp==NULL)

    return;

    else

    {

      while( (c=getche())!=‘*’)

      fputc(c,fp);

    }

    fclose(fp);

    }

  6.  

    void main()

    {

    FILE *fp;

    char ch;

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

    clrscr();

    if(fp==NULL)

    {

      printf(“File Not Found”);

      exit(0);

    }

    fseek(fp,21,SEEK_SET);

    ch=fgetc(fp);

    clrscr();

    rewind(fp);

    for(; 😉

    {

      printf(“%d\n”,ftell(fp));

      ch=fgetc(fp);

    }

    }

VII  Find the bug/s in the following program/s:

  1.  

    # include <process.h>

    void main()

    {

    FILE *fp;

    char c=‘ ’;

    clrscr();

    fp=fopen(“data.txt”,“w”);

    if(fp==NULL)

    {

      printf(“Cannot read file”);

      exit(0);

    }

    printf(“Write data & to stop press . : ”);

    while(c!=‘.’)

    {

      c=getche();

      fputc(c,fp);

    }

    printf(“\n Contents Read :”);

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

    while(!feof(fp))

    printf(“%c”,getc(fp));

    }

  2.  

    # include <process.h>

    void main()

    {

      FILE *fp;

    char c= ‘ ’;

    clrscr();

    fp=fopen(“data.txt”,“w”);

    if(fp==NULL)

    {

      printf(“Cannot read file”);

      exit(0);

    }

      printf(“Write data & to stop press . : ”);

      while (c!=‘.’)

      {

        c=getche();

        fputc(c,fp);

      }

      printf(“\n Contents

      Read :”);

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

      while(!feof(fp))

      printf(“%c”,getc(fp));

      }

  3.  

    void main()

    {

    FILE *fp;

    char text[30];

    clrscr();

    fp=fopen(“text.txt”,“w”);

    clrscr();

    puts(“\n Enter Text Here”);

    gets(text);

    fprintf(“%s”,text);

    }

  4.  

    # include <process.h>

    void main()

    {

    FILE *fp;

    char c;

    clrscr();

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

    if(fp==NULL)

    {

      printf(“\n cannot open file”);

    }

    while( (c=getc(fp)) !=EOF)

    printf (“%c”,c);

    fclose(fp);

    }

  5.  

    void main()

    {

    FILE *fr;

    Char c, file[]=“text.txt”;

    Fr=fopen(file,“w”);

    clrscr();

    while(feof(fr))

    {

      c=fgetc(fr);

      if (ferror(fr))

      {

        perror(file);

        exit(0);

      }

      else

      printf(“%c”,c);

    }

    fclose(fr);

    }

  6.  

    void main()

    {

    char buff[10];

    clrscr();

    setbuf(stdout,buff);

    printf(“This Book is very good”);

    fflush (stdout);

    }

ANSWERS

I  True or false:

Q.

Ans.

1.

T

2.

T

3.

F

4.

F

5.

T

6.

T

7.

T

8.

F

9.

T

10.

T

11.

F

12.

T

13.

F

14.

T

15.

T

16.

F

17.

T

18.

T

19.

F.

II  Match the following correct pairs given in Group A with Group B:

  1.  

    Q.

    Ans.

    1.

    B

    2.

    A

    3.

    D

    4.

    C
  2.  

    Q.

    Ans.

    1.

    B

    2.

    D

    3.

    A

    4.

    C

III  Select the appropriate option from the multiple choices given below:

Q.

Ans.

1.

a

2.

a

3.

a

4.

a

5.

c

6.

a

7.

a

VI  What will be the output/s of the following program/s?

Q.

Ans.

1.

Contents of file before appending :
String is terminated with ‘\0’.
Enter string to append :
This character is called as NULL character.
Contents of file After appending :
String is terminated with ‘\0’.
This character is called as NULL character.

2.

Write data & to stop press ‘.’: ABCDEFGHIJK.
Contents read: ABCDEFGHIJK.

3.

Write data & to stop press ‘.’ : This is append and read mode.
Contents read: This is append and read mode.

4.

Enter Text Here: Have a nice day.

5.

Have a nice day.

6.

File Not Found.

VII  Find the bug/s in the following program/s:

Q.

Ans.

1.

After writing data file should be closed.

2.

The file opening mode “W” is invalid.

3.

The file pointer is missing in fprintf().

4.

In if() statement exit(0) statement is required.

5.

while (!eof(fr)) is correct condition.

6.

The size of the buffer is to small.