• UNIT 14: FILE HANDLING IN C++

    Key unit competency

    Open, close, create a data file in C++ and read, write and append data to Files

    Introductory Activity

    Observe the figure below and answer the following questions.

    1. What do you understand by file?

    2. Provide two examples of files.

    3. How do we store files?

    4. What do you understand by file size?

    5. Create “BOOK.txt” file.

    6. Put some text in the file created above

    7. Write a function in C++ to count the number of uppercase alphabets

    present in a text file “BOOK.txt”.

    8. Write a function in C++ to count letters present in a text file “BOOK.txt”.

    9. Write a function in C++ to count digits present in a text file “BOOK.txt”.

    10. Write a function in C++ to count white spaces present in a text file

    “BOOK.txt”

    11. Write a function in C++ to count vowels present in a text file “BOOK.txt”.

    14.1. Understanding files

    Learning Activity 14.1.

    1. Explain the types of files

    2. Provide one example of each file type

    3. Discuss the role of file name

    4. Differenciate text file from binary files

    Every program or sub-program consists of two major components: algorithm and

    data structures.

    The algorithm takes care of the rules and procedures required for solving the

    problem and the data structures contain the data. The data is manipulated by the

    procedures for achieving the goals of the program.

    A data structure is volatile by nature in the sense that its contents are lost as soon

    as the execution of the program is over. Similarly, an object also loses its states after

    the program is over. To store permanently the data or to create persistent objects t

    becomes necessary to store the same in a special data structure called file. The file

    can be stored on a second storage media such as hard disk. In fact, vary large data is

    always stored in a file.

    14.1.1. File

    A file is a self-contained piece of information available to the operating system and

    any number of individual programs. A computer file can be thought of much like a

    traditional file that one would find in an office’s file cabinet. Just like an office file,

    information in a computer file could consist of basically anything.

    Whatever program uses an individual file is responsible for understanding its

    contents. Similar types of files are said to be of a common “format.” In most cases,

    the easiest way to determine a file’s format is to look at the file’s extension.

    Each individual file in Windows will also have a file attribute which sets a condition

    to the specific file. For example, you can’t write new information to a file that has

    the read-only attribute turned on.

    A file name is just the name that a user or program gives the file to help identify what

    it is. An image file may be named something (example of file name with extension:

    kids-lake-2017.jpg). The name itself doesn’t affect the contents of the file, so even

    if a video file is named something like image.mp4, it doesn’t mean it’s suddenly a

    picture file.

    Files in any operating system are stored on hard drives, optical drives, and other

    storage devices. The specific way a file is stored and organized is referred to as a file

    system.

    Examples of Files:

    An image copied from a camera to a computer may be in the JPG or TIF format.

    These are files in the same way that videos in the MP4 format, or MP3 audio files, are

    files. The same holds true for DOC/DOCX files used with Microsoft Word, TXT files

    that hold plain text information, etc.

    Though files are contained in folders for organization (like the photos in your Pictures

    folder or music files in your iTunes folder), some files are in compressed folders, but

    they’re still considered files. For example, a ZIP file is basically a folder that holds

    other files and folders but it actually acts as a single file.

    Another popular file type similar to ZIP is an ISO file, which is a representation of a

    physical disc. It’s just a single file but it holds all the information found on a disc, like

    a video game or movie.

    From these few examples, it is clear that not all files are alike, but they all share a

    similar purpose of holding information together in one place.

    14.1.2. Types of files:

    a. A. Binary Files

    Binary files typically contain a sequence of bytes, or ordered groupings of eight bits.

    When creating a custom file format for a program, a developer arranges these bytes

    into a format that stores the necessary information for the application. Binary file

    formats may include multiple types of data in the same file, such as image, video,

    and audio data. This data can be interpreted by supporting programs, but will show

    up as garbled text in a text editor. Below is an example of a .PNG image file opened

    in an image viewer and a text editor.

    j

    As it is seen, the image viewer recognizes the binary data and displays the

    picture. When the image is opened in a text editor, the binary data is converted

    to unrecognizable text. However, some of the text is readable. This is because the

    PNG format includes small sections for storing textual data. The text editor, while

    not designed to read this file format, still displays this text when the file is opened.

    Many other binary file types include sections of readable text as well. Therefore, it

    may be possible to find out some information about an unknown binary file type by

    opening it in a text editor.

    Binary files often contain headers, which are bytes of data at the beginning of a

    file that identifies the file’s contents. Headers often include the file type and other

    descriptive information. For example, in the image above, the “PNG” text indicates

    the file is a PNG image. If a file has invalid header information, software programs

    may not open the file or they may report that the file is corrupted.

    b. Text Files

    Text files are more restrictive than binary files since they can only contain textual

    data. However, unlike binary files, they are less likely to become corrupted. While

    a small error in a binary file may make it unreadable, a small error in a text file may

    simply show up once the file has been opened. This is one of reasons Microsoft

    switched to a compressed text-based XML format for the Office 2007 file types.

    Text files may be saved in either a plain text (.TXT) format or rich text (.RTF) format. A

    typical plain text file contains several lines of text that are each followed by an Endof-

    Line (EOL) character. An End-of-File (EOF) marker is placed after the final character,

    which signals the end of the file. Rich text files use a similar file structure, but may also

    include text styles, such as bold and italics, as well as page formatting information.

    Both plain text and rich text files include a (character encoding| character encoding)

    scheme that determines how the characters are interpreted and what characters

    can be displayed.

    Since text files use a simple, standard format, many programs are capable of reading

    and editing text files. Common text editors include Microsoft Notepad and WordPad,

    which are bundled with Windows, and Apple TextEdit, which is included with Mac

    OS X.

    c. The difference between binary and text files

    All files can be categorized into one of two file formats: binary or text. The two

    file types may look the same on the surface, but they encode data differently. While

    both binary and text files contain data stored as a series of bits (binary values of

    1s and 0s), the bits in text files represent characters, while the bits in binary files

    represent custom data.

    While text files contain only textual data, binary files may contain both textual and

    custom binary data.

    Application Activity 14.1.

    1. Discuss text files and provide two examples.

    2. Describe binary files and provide two examples.

    3. Explain the role of file extension

    4. Where are files stored?

    14.2. File Streams

    k

    k

    14.2.1. Introduction

    One of the great strengths of C++ is its I/O system, IO Streams. As Bjarne Stroustrup

    says in his book “The C++ Programming Language”, “Designing and implementing

    a general input/output facility for a programming language is notoriously difficult”.

    He did an excellent job, and the C++ IOstreams library is part of the reason for C++’s

    success. IO streams provide an incredibly flexible yet simple way to design the input/

    output routines of any application.

    IOstreams can be used for a wide variety of data manipulations to the following

    features:

    A ‘stream’ is internally nothing but a series of characters. The characters may be either

    normal characters (char) or wide characters (wchar_t). Streams provide users with a

    universal character-based interface to any type of storage medium (for example,

    a file), without requiring the to know the details of how to write to the storage

    medium. Any object that can be written to one type of stream, can be written to all

    types of streams. In other words, as long as an object has a stream representation,

    any storage medium can accept objects with that stream representation.

    Streams work with built-in data types, and the user can make user-defined types

    work with streams by overloading the insertion operator (<<) to put objects into

    streams, and the extraction operator (>>) to read objects from streams.

    The stream library’s unified approach makes it very friendly to use. Using a consistent

    interface for outputting to the screen and sending files over a network makes life

    easier. The programs below will show what is possible.

    14.2.2. Meaning of input and output

    The input is whatever the user enters through a keyboard or any other input devices

    while output what is written (displayed) on a output device being screen, printer

    or file. The information input or output is considered as a stream of characters.

    Suppose that the user enters the number 7479. The set of 4 characters: ‘7’, ‘4’, ‘7’ and

    ‘9’ taken as input can be considered as numbers or a string. the input characters

    must be put into a recognizable data type for them to be of any use other than as a

    character array.

    IO streams not only define the relation between a stream of characters and the

    standard data types but also allows the user to define a relationship between a

    stream of characters and its classes. It also allows the user nearly limitless freedom

    to manipulate those streams both using object oriented interfaces and working

    directly on character buffers when necessary

    14.2.3. Working with streams

    Streams are serial interfaces to storage, buffers files, or any other storage medium.

    The difference between storage media is intentionally hidden by the interface;

    the usermay not even know what kind of storage he/she is working with but the

    interface is exactly the same.

    The “serial” nature of streams is a very important element of their interface. The

    usercannot directly make random access: random reads or writes in a stream (unlike,

    say, using an array index to access any wanted value) although he/she can seek to a

    position in a stream and perform a read at that point.

    Using a serial representation gives a consistent interface for all devices. Many devices

    have the capability of both producing and consuming data at the same time; if data

    is being continually produced, the simplest way to think about reading that data is

    by doing a fetch of the next characters in a stream. If that data hasn’t been produced

    yet (the user hasn’t typed anything, or the network is still busy processing a packet),

    he/she waits for more data to become available, and the read will return that data.

    Even if he/she tries to seek past the end (or beginning) of a stream, the stream

    pointer (i.e. get or put pointer) will remain at the boundary, making the situation

    safe. (Compare this with accessing data off the end of an array, where the behavior

    is undefined.)

    The underlying low-level interface that corresponds to the actual medium very

    closely is a character buffer (the stream buffer, technically called the streambuf),

    which can be thought of as the backbone of the stream. Being a buffer, it does not

    hold the entire content of the stream, if the stream is large enough, so you can’t use

    it for random access.

    14.2.4. The most important of the basic stream operations are

    First, the stream is initialized with the appropriate type (like a std::string for a

    stringstream and the filename for an fstream) of values and suitable modes (like

    ios::in for input and ios::out for output and many more depending on the type of the

    stream).

    After that, the user can specify where the I/O should occur, through the get and put

    pointers. Depending on how the stream is opened, the location may already be set

    appropriately (for example, if a file is opened with ios::app, the get pointer sets at the

    end of the stream, allowing appends).

    14.2.5. Functions of file stream classes

    14.2.5.1. Introduction

    In this brief introduction, the basic operations on both text and binary files are

    discussed so that the functions to carry out these tasks are well understood.

    The Basic File Operations on Text Files are:

    • Creating an empty file – First time when a file is created with some valid

    filename it is empty therefore it contains only EOF marker and a location

    pointer pointing to it.

    • Opening a file – A file is opened for reading/writing or manipulation of

    data on it. If a file exists then only it can be opened , when a file is opened

    the location pointer points to the Beginning of file.

    • Closing a file – After the file operations done , the file should be closed. If

    we don’t close the file it gets automatically closed when the program using

    it comes to an end.

    • Writing text into file – Once a file is created , data elements can be stored

    to it permanently. The already existing contents are deleted if we try to

    write data to it next time, rather we can append data to it and keep the

    existing data.

    • Reading of text from an already existing text file (accessing sequentially)

    • Manipulation of text file from an already existing file – An existing file

    is opened first and then the manipulation is done in sequential order. for

    example – counting of words.

    • Detecting EOF – When the data from the file is read in sequential order, the

    location pointer will reach to the end of file. After reaching at the EOF no

    attempt should be made to read data from the file.

    • Copying of one text file to other text file

    The Binary file operations are:

    1. Creation of file – A binary file is always opened in binary mode for both

    reading or writing. Upon successful creation, the pointer is set to the

    beginning of the file.

    2. Writing data into file – A binary file is opened in output mode for writing

    data in it. A binary file contains non readable characters and writeegg

    function is used to write the records into file.

    3. Searching for required data from file – a binary file is opened in input

    mode for searching data. The file can be read sequentially one by one each

    record or randomly by going to that particular location.

    4. Appending data to a file – appending means addition of new records to

    an already existing file.

    5. Insertion of data in sorted file

    6. Deletion of data

    7. Modification/Updation of data

    14.2.6. Components of c++ to be used with file handling

    In C++ file input/output facilities are performed by a header file fstream.h, which

    exists in the C++ standard library. C++ provides specific classes for dealing with user

    defined streams. Every file in C++ is linked to a stream. A stream must be obtained

    before opening a file. The file fstream.h is inherited from iostream.h, thus includes

    all the classes included in iostream.h .

    User defined streams – The four classes for file Input/Output are :

    a. Ifstream – derived from istream and used for file input(reading). It inherits

    the functions get(), getline() and read() and functions supporting random

    access(seekg() and tellg() and >> operator. It also contains open(),close()

    and eof().

    b. ofstream – derived from ostream and used for file output(writing). It

    inherits the functions put() and write() functions along with functions

    supporting random access (seekp() and tellp() from ostream class. It also

    contains open(),close() and eof().

    c. fstream – derived form iostream and used for both input and output.

    It inherits all the functions from istream and ostream classes through

    iostream.h.

    d. Filebuf – it sets the buffers to read and write and contains close() and

    open() member functions in it.

    14.2.7. Text File Operations

    14.2.7.1. Reading Operation

    a. Reading a File Character by character (including space,’\n’,’\t’)

    Example:

    Observe the following C++ program, interpret it and thereafter run it.

    #include <iostream>

    #include <fstream>

    #include <string>

    usingnamespace std;

    int main () {

    string line;

    ifstream myfile (“example.txt”);

    if (myfile.is_open())

    {

    while ( getline (myfile,line) )

    {

    cout << line <<’\n’;

    }

    myfile.close();

    }

    else cout <<”Unable to open file”;

    return 0;

    }

    Explanations on how to write a program that reads from a file.

    j

    l

    k

    k

    14.2.7.2. Writing in Text File

    Example:

    Observe the following C++ program, interpret it and thereafter run it:

    #include <iostream>

    #include <fstream>

    usingnamespace std;

    int main () {

    ofstream myfile;

    myfile.open (“example.txt”);

    myfile <<”Writing this to a file.\n”;

    myfile.close();

    return 0;

    }

    k

    Example:

    Observe the following C++ program, interpret it and thereafter run it:

    #include <iostream>

    #include <fstream>

    usingnamespace std;

    int main () {

    ofstream myfile (“example.txt”);

    if (myfile.is_open())

    {

    myfile <<”This is a line.\n”;

    myfile <<”This is another line.\n”;

    myfile.close();

    }

    else cout <<”Unable to open file”;

    return 0;

    }

    k

    Binary Files are also called fixed length files or packed files as all the fields in a binary

    file occupy fixed number of bytes.

    For Opening files C++ provides mechanism for opening file in different modes:

    l

    Note:

    A file can be opened in more than one modes by making use of pipe sign as follows:

    fstream file(“ABC”,ios::in|ios::binary|ios::out);

    l

    a. Writing class object to binary File (assuming student class ) and

    function is a member function

    j

    b. Writing Structure object to binary File (assuming student is structure,

    containing name and avg as members)

    j

    14.2.7.4. Reading a Binary File

    Example:

    Observe the following program, interpret it and run it:

    #include <iostream>

    #include <fstream>

    usingnamespace std;

    int main () {

    streampos size;

    char * memblock;

    ifstream file (“example.bin”, ios::in|ios::binary|ios::ate);

    if (file.is_open())

    {

    size = file.tellg();

    memblock = newchar [size];

    file.seekg (0, ios::beg);

    file.read (memblock, size);

    file.close();

    cout <<”the entire file content is in memory”;

    delete[] memblock;

    }

    else cout <<”Unable to open file”;

    return 0;

    }

    a. Sequential reading

    Sequential reading means reading record one by one until end of file and all the

    records are displayed.

    k

    Displaying selected records -This is condition based display, where the condition

    is checked after reading. If the reading is concerned with reading class objects then

    there will be a function in class as a public member which will return that particular

    value that is to be evaluated. If the structure instance is to be read from file then

    the normal comparison can be done after executing the file read statement. If the

    condition is true then call display function or display the record.

    Display Records from file where average marks are greater than 60

    k

    b. Random Access

    Up till now we had been writing and reading the files in sequential manner but

    binary files, being fixed length files, provides liberty to perform read and write

    operations randomly. C++ provides functions for it. When you open a file operating

    system assigns two exclusive pointers to file object. In C++ these pointers are called

    get pointer(input) and put pointer(output) . These pointers provide you the facility

    to move to the desired place in the file to perform read, write operations. The get

    pointer specifies a location from where the current reading operation is initiated.

    The put pointer specifies a location where the current write operation will take place.

    14.2.7.5. Functions for manipulating file pointers

    k

    k

    a. Random record reading

    File pointer position is set according to the record number to be displayed. The file

    pointer directly can be set to the position using seekg().

    Note:- when file is opened in input or output mode the file pointer is at the starting

    i.e. at 0 position. In append mode the file pointer is at the end of file, and the writing

    continues by adding the records.

    void readrec()

    {

    ifstreamfin(“stud.dat”,ios::binary|ios::in);

    stud s;

    int rec;

    cout<<”enter the record you want to display”;

    cin>>rec;

    fin.seekg((rec-1)*sizeof(stud),ios::beg); // by default ios::beg is default argument

    fin.read((char*)&s,sizeof(stud));

    s.display();

    getch();

    }

    b. Updation of record in existing file

    In this the record to be updated is asked from the user, then appropriate position of

    file pointer is obtained and pointer is set and writes operation is performed.

    Eg.– writing a program to update structure/class object to update.

    c. Insertion in Sorted file

    The record to be inserted in a sorted file is accepted as a separate object. The file

    in which the record is to be inserted, is opened in input mode. The records with

    record key smaller than the record key to be inserted are copied to temporary file

    and then record to be inserted is copied, following with rest of the records if any.

    After that original file is removed using remove() and temporary file is renamed with

    the original name with rename().

    d. Deletion of record from file

    The logic of deleting record is:

    1. Accept the record key for the record you want to delete.

    2. Read the file sequentially , from which the record is to be deleted and

    copied down the records to temporary file except the record you want to

    delete (by comparing the record value)

    3. Remove the original file and rename the temporary file with the original

    file name.

    Sorting the records of an existing file - First the records in the file are counted . an

    array of objects is created dynamically / statically with the approx. index value as

    compared to number of records.

    And read the file using the following statement:

    while (fin.read(char*)&obj[i++],sizeof(class))); After reading the file , sort the array

    with any sorting technique(Bubble/Insertion/Selection) Then write the sorted array

    in to the file opened in output mode.

    Notes:-

    1. Multiple File Handling-

    In this case the point to remember is:

    a)Identify the file mode to be opened .

    b) One object can open only one file at a time.

    2. Sizeof() operator gives the sizeof data type.

    3. The data written to a file using write() can only be read accurately using

    read().

    4. The files are closed using destructor of file object, if not closed using

    close(). It is must to close the file. If the file pointer is opening another file

    in the same program otherwise it is a good practice to use close().

    Learning Activity 14.2.

    1. Write a C++ program to open and read text from a text file character

    by character in C++. We have a file named “test.txt”, this file contains

    following text:

    Hello friends, how are you?

    I hope you are fine and learning well.

    Thanks.

    We will read text from the file character by character and display it on the output

    screen.

    2. Using C++, create a file and then write some text into that file, after

    writing text file it will be closed and again file will open in read mode,

    read all written text.

    3. Provide a C++ program to write and read variable’s values in/from text

    file. Here you will show how to write values in file and how to access

    them.

    4. Give a C++ program to write and read values through object in/from

    text files. Demonstrate how to write object value in file and how to

    access them.

    5. The function tellg() and tellp() are predefined functions which tells

    (returns) the position of the get and put pointers. Write a C++ program

    to demonstrate example of tellg() and tellp() function.

    14.2.7.6. Closing a file

    a. Detecting the End of a File

    The eof() member function reports when the end of a file has been encountered.

    if (inFile.eof())

    inFile.close();

    A File is closed by disconnecting it with the stream it is associated with. The closeegg

    function is used to accomplish this task.

    Syntax:

    Stream_object.closeegg;

    Example :

    fout.close();

    eof egg Function

    This function determines the end-of-file by returning true (non-zero) for end of file

    otherwise returning false(zero).

    Syntax

    Stream_object.eofegg;

    Example :

    fout.eofegg;

    b. Testing for Open Errors

    dataFile.open(“cust.dat”, ios::in);

    if (!dataFile)

    {

    cout << “Error opening file.\n”;

    }

    Another way to Test for Open Errors

    dataFile.open(“cust.dat”, ios::in);

    if (dataFile.fail())

    {

    cout << “Error opening file.\n”;

    }

    Note on eof():

    In C++, “end of file” doesn’t mean the program is at the last piece of information

    in the file, but beyond it. The eof() function returns true when there is no more

    information to be read.

    Application activity 14.3.:

    1. Write a C++ program that demonstrates the declaration of an fstream

    object and the opening of a file.

    2. Write a C++ program that demonstrates the opening of a file at the time

    the file stream object is declared.

    3. Write a C++ program that demonstrates the close function.

    4. Write C++ program that uses the << operator to write information to a

    file. The Program Screen Output will display:

    File opened successfully.

    Now writing information to the file.

    Done.

    And the Output to file demofile.txt will be:

    Jones

    Smith

    Willis

    Davis

    5. This program writes information to a file, closes the file, then reopens it

    and appends more information.

    6. Write a program to create a binary file ‘student.dat’ using structure.

    7. Program to read a binary file ‘student.dat’ display records on monitor.

    8. Write the program that writes the information to a file, closes the file,

    then reopens it and appends more information.

    9. Provide a C++ program that will demonstrate how to write and read

    time in/from binary file using fstream. Remember that there will be two

    functions: writeTime() - that will write time into the file and readTime() -

    that will read time from the file. In the program, there are two things to

    be noticed, how time will be formatted into a string (using sprintf ) and

    how time values will be extracted from the string (using sscanf ).

    10. Write a C++ program to read an employee’s details from keyboard

    using class and object then write that object into the file. The program

    will also read the object and display employee’s record on the screen.

    This program is using following file stream (file handling) functions.

    There will be the following functions:

    •• file_stream_object.open() to open a file

    •• file_stream_object.close() to close the file

    •• file_stream_object.write() to write an object into the file

    •• file_stream_object.read() to read object from the file

    In this program there are following details to be read through Employee class

    •• Employee ID

    •• Employee Name

    •• Designation

    •• Date of joining

    •• Date of birth

    Observe the program segment carefully and answer the question that follows:

    class stock

    {

    int Ino, Qty; Char Item[20];

    public:

    void Enter() { cin>>Ino; gets(Item); cin>>Qty;}

    void issue(int Q) { Qty+=0;}

    void Purchase(int Q) {Qty-=Q;}

    int GetIno() { return Ino;}

    };

    void PurchaseItem(int Pino, int PQty)

    { fstream File;

    File.open(“stock.dat”, ios::binary|ios::in|ios::out);

    Stock s;

    int success=0;

    while(success= = 0 && File.read((char *)&s,sizeof(s)))

    {

    If(Pino= = ss.GetIno())

    {

    s.Purchase(PQty);

    _______________________ // statement 1

    _______________________ // statement 2

    Success++;

    }

    }

    if (success = =1)

    cout<< “Purchase Updated”<<endl;

    else

    cout<< “Wrong Item No”<<endl;

    File.close() ;

    }

    a. Statement 1 to position the file pointer to the appropriate place so that

    the data updating is done for the required item.

    b. Statement 2 to perform write operation so that the updating is done in

    the binary file.

    1. Write C++ program that uses the file stream object’s eof() member

    function to detect the end of the file.

    Summary:

    Let us talk briefly about some key concepts of file streams discussed here above:

    filebuf

    It sets the buffer to read and write, it contains close() and open() member functions

    on it.

    fstreambase

    This is the base class for fstream and, ifstream and ofstream classes. therefore it

    provides the

    common function to these classes. It also contains open() and close() functions.

    ifstream

    Being input class it provides input operations it inherits the functions getegg, getline(

    ), readegg,

    and random access functions seekgegg and tellgegg functions.

    ofstream

    Being output class it provides output operations it inherits putegg, writeegg and random

    access

    functions seekpegg and tellpegg functions.

    fstream

    It is an I/O class stream, it provides simultaneous input and output operations.

    File modes

    Meaning of file mode:

    The file mode describes how a file is to be used ; to read from it, write to it, to append

    and so on

    Syntax

    Stream_object.open(“filename”,mode);

    File Modes are briefly discussed here below:

    ios::out: It open file in output mode (i.e write mode) and place the file pointer in

    beginning, if

    file already exist it will overwrite the file.

    ios::in: It open file in input mode (read mode) and permit reading from the file.

    ios::app: It open the file in write mode, and place file pointer at the end of file i.e to

    add new

    contents and retains previous contents. If file does not exist it will create a new file.

    ios::ate: It open the file in write or read mode, and place file pointer at the end of

    file i.e input/

    output operations can performed anywhere in the file.

    ios::trunc: It truncates the existing file (empties the file).

    ios::nocreate: If file does not exist this file mode ensures that no file is created and

    open() fails.

    ios::noreplace If file does not exist, a new file gets created but if the file already

    exists, the

    open() fails.

    ios::binary Opens a file in binary mode.

    Logic to read a text file:

    • 1. Open file in read/input mode using std::in

    • 2. Check file exists or not, if it does not exist terminate the program

    • 3. If file exist, run a loop until EOF (end of file) not found

    • 4. Read a single character using cin in a temporary variable

    • 5. And print it on the output screen

    • 6. Close the file

    End unit assessment

    1. Write a function in C++ to search for details (Phoneno and Calls) of those

    Phones which have more than 800 calls from binary file “phones.dat”.

    Assuming that this binary file contains records/ objects of class Phone,

    which is defined below.

    class Phone

    {

    Char Phoneno[10]; int Calls;

    public:

    void Get() {gets(Phoneno); cin>>Calls;}

    void Billing() { cout<<Phoneno<< “#”<<Calls<<endl;}

    int GetCalls() {return Calls;}

    };

    2. Write a function in C++ to add new objects at the bottom of a binary file

    “STUDENT.DAT”, assuming the binary file is containing the objects of the

    following class:

    class STUD

    {

    int Rno;

    char Name[20];

    public:

    void Enter()

    {cin>>Rno;gets(Name);}

    void Display(){cout<<Rno<<Name<<endl;}

    };

    3. Given a binary file PHONE.DAT, containing records of the following class

    type

    class Phonlist

    {

    char name[20];

    char address[30];

    char areacode[5];

    char Phoneno[15];

    public:

    void Register()

    void Show();

    void CheckCode(char AC[])

    {return(strcmp(areacode,AC);

    };

    Write a function TRANSFERegg in C++, that would copy all those records which are

    having areacode as “DEL” from PHONE.DAT to PHONBACK.DAT.

    4. Given a binary file SPORTS.DAT,containg records of the following structure

    type:

    struct Sports

    {

    char Event[20] ; char Participant[10][30] ;

    } ;

    Write a function in C++ that would read contents from the file SPORTS.DAT and

    creates a file named ATHLETIC.DAT copying only those records from SPORTS.DAT

    where the event name is “Athletics”.

    5. 5.Given a binary file TELEPHON.DAT, containing records of the following

    class Directory :

    class Directory { char Name[20] ; char Address[30] ;

    char AreaCode[5] ; char phone_No[15] ; public ;

    void Registeregg ; void Showegg ;

    int CheckCode(char AC[ ])

    { return strcmp(AreaCode, AC) ;

    }

    } ;

    Write a function COPYABCegg in C++, that would copy all those records having

    AreaCode as “123” from TELEPHON.DAT to

    TELEBACK.DAT.

    BIBLIOGRAPHY

    1. National Curriculum Development Centre(NCDC). (2011). ICT Syllabus for

    Upper Secondary. Kigali.

    2. applications, D. M., Tumkur, S. I., & Bangalore., V. B.-P. (n.d.). Visual Basic 6.0

    A simple Approach . 3rd Main Road, Gandhinagar, Bangalore- 5600 009:

    Sapna Book House.

    3. Byron S. GOTTFRIED, P. (n.d.). schaum’s ouTlines Visual Basic.

    4. Chopra, R. (2009). OPERATING SYSTEM (A PRACTICAL APP). New Delhi: S

    Chand & Company Pvt Ltd.

    5. Dhamdhere, D. (2006). OPERATING SYSTEMS: A CONCEPT- BASED

    APPROACH, 2E. New Delhi: Tata McGraw Hill Publishing Company Limited.

    6. Dhotre, I. A. (2009). OPERATING SYSTEMS. New Delhi: Technical

    Publications Pune.

    7. Garrido, Schlesinger, Hoganson. (2013). MODERN OPERATING SYSTEMS

    2ND EDITION. USA: Library of Congress Cataloging in Publication Data.

    8. Godbole. (2011). OPERATING SYSTEM 3E. New Delhi: Tata McGraw Hill

    Education Private Limited.

    9. Haggard, G., & Shibata, w. H. (2013). Introduction: Visual Basic6.0.

    bookboon.com.

    10. Halvorson, M. (1999). Learn Microsoft Visual Basic 6.0 Now.

    11. Khurana, R. (2011). OPERATING SYSTEMS (FOR ANNA). New Delhi: Vikas

    Publishing Pvt Ltd.

    12. McGrath, M. (2008). Visual Basic in Easy Steps.

    13. MINEDUC. (2008). Geographic and Information Systems(GIS). Kigali.

    14. MINEDUC. (2013). Education Sector Strategic Plan . Kigali.

    15. MINEDUC. (2014). ICT in Education Policy. Kigali: MINEDUC.

    16. Ministry of Education, Sengapore,2007. (2007). Computer Applications

    Syllabus(Lower Secondary Technical). Sengapore: Curriculum Planning&

    Development Division.

    17. MYICT. (2011). National ICT strategy and plan NICI III-2015.Kigali.

    18. National Curriculum Development Centre(NCDC). (2006). ICT syllabus for

    Lower Secondary Education. Kigali.

    19. Norton, P. (1998). Guide to Visual Basic 6.0.

    20. Pearson Education. (2010). Computer Concepts.

    21. Sharma, Varshney, Shantanu. (2010). DESIGN AND IMPLEMENTATION OF

    OPERATING SYSTEM. New Delhi: University Science Press.

    22. University, M. (n.d.). Project NameSystem User Requirements. Project

    NameSystem User Requirements; Projects Office.

    23. University, O. S. (2018). Single Processor Scheduling Algorithms. Retrieved

    March Tuesday, 2018, from Department of Computer Science and

    Engineering: http://web.cse.ohio-state.edu/~agrawal.28/660/Slides/jan18.

    pdf

    UNIT 13: MULTIMEDIAASSESSMENT