We need you!

We're working hard on the next version of Developer Fusion. Let us know what you think we should be up to!

Members

Technology Zones

Articles

Hosted By

MaximumASP

Info

C++ add, delete, list and modify using binary file ".dat"

Last post 06-19-2008 4:07 PM by Mohammad Rastkar. 15 replies.
Page 1 of 2 (16 items) 1 2 Next >
Sort Posts: Previous Next
  • 01-31-2007 6:07 AM

    • joan
    • Not Ranked
    • Joined on 01-16-2007
    • New Member
    • Points 50

    C++ add, delete, list and modify using binary file ".dat"

    Hello,

             Do anyone know how to create a binary file ".dat"?  I know how to use the C Programming to do it, but for C++ I have no ideal.  Do anyone have the C++ program source code which able to add, delete, list and modify in the binary file ".dat"?

    Thank you

    Joan Choong

     

     

    • Post Points: 10
  • 01-31-2007 6:39 AM In reply to

    a Question...

    • What you want? Infos about :
    1. Working with files (binary or text) in C++ ?
    2. Specific operations in '.dat' files (in C++) ?
    • Do you want detailed infos or just some points ? (have any references like books, MSDN ?)
    - I don't have Time To waste The Time!
    • Post Points: 10
  • 01-31-2007 7:11 AM In reply to

    • joan
    • Not Ranked
    • Joined on 01-16-2007
    • New Member
    • Points 50

    Re: a Question...

    Hello Mohammad Rastkar,

                         Actually I want a binary file (as database) but not text file in C++ which can add, delete, list and modify.  ".dat" file is one of the database file in C++.  I need the detailed infos.  Some of the C++ books I had go through but can't find it.

    Please help if you know about it.

    Thanks,

    Joan Choong

    • Post Points: 10
  • 02-01-2007 8:17 AM In reply to

    Star [*] Infos...

    OK!

    Hello joan...

    -> I hope the following infos will help you...

    -> Below I've separated the infos in three parts :

    -> If you want more infos -> Just tell me Wink


    < Points >

    • include the 'fstream' file : #include <fstream> (You should include this file for all file interactions).
    • Open the file with 'open' method, that has 'ios::binary' for second parameter. (the file extension has NO effect on file contents [you can use files without extension], the 'open' method specifies the interaction mode (binary,text,..))
    • Use one of these ways, for I/O from file :
      1. Just like the standard 'iostream' (cin & cout), you can use '>>' and '<<' with language types (int, cahr, ..) and overload
      these operators to use with your own types.
      2. You can also use Structures (struct), and input them into file with 'write' method, and have an output with 'read' method.                                                                                                                           
      3.You can interact with a binary file as text (and vice versa) and Using 'get', 'put',... methods that is used with text files ('getline' will work unexpected in binary parts of file).
    • when your interaction with file ends, close the file with 'close' method.

     

    < Detailed >

    fstream::fstream

    fstream();

    fstream( const char* szName, int nMode, int nProt = filebuf::openprot );

    fstream( filedesc fd );

    fstream( filedesc fd, char* pch, int nLength );

    Parameters

    szName

    The name of the file to be opened during construction.

    nMode

    An integer that contains mode bits defined as ios enumerators that can be combined with the bitwise OR ( | ) operator. The nMode parameter must have one of the following values:

    • ios::app   The function performs a seek to the end of file. When new bytes are written to the file, they are always appended to the end, even if the position is moved with the ostream::seekp function.

    • ios::ate   The function performs a seek to the end of file. When the first new byte is written to the file, it is appended to the end, but when subsequent bytes are written, they are written to the current position.

    • ios::in   The file is opened for input. The original file (if it exists) will not be truncated.

    • ios::out   The file is opened for output.

    • ios::trunc   If the file already exists, its contents are discarded. This mode is implied if ios::out is specified, and ios::ate, ios::app, and ios:in are not specified.

    • ios::nocreate   If the file does not already exist, the function fails.

    • ios::noreplace   If the file already exists, the function fails.

    • ios::binary   Opens the file in binary mode (the default is text mode).

      Note that there is no ios::in or ios::out default mode for fstream objects. You must specify both modes if your fstream object must both read and write files.

    nProt

    The file protection specification; defaults to the static integer filebuf::openprot, which is equivalent to the operating system default, filebuf::sh_compat, under MS-DOS. The possible nProt values are as follows:

    • filebuf::sh_compat   Compatibility share mode (MS-DOS only).

    • filebuf::sh_none   Exclusive mode — no sharing.

    • filebuf::sh_read   Read sharing allowed.

    • filebuf::sh_write   Write sharing allowed.

      The filebuf::sh_read and filebuf::sh_write modes can be combined with the logical OR ( || ) operator.

    fd

    A file descriptor as returned by a call to the run-time function _open or _sopen. filedesc is a typedef equivalent to int.

    pch

    Pointer to a previously allocated reserve area of length nLength. A NULL value (or nLength = 0) indicates that the stream will be unbuffered.

    nLength

    The length (in bytes) of the reserve area (0 = unbuffered).

    Remarks

    The four fstream constructors are:

    • fstream()   Constructs an fstream object without opening a file.

    • fstream( const char*, int, int )   Contructs an fstream object, opening the specified file.

    • fstream( filedesc )   Constructs an fstream object that is attached to an open file.

    • fstream( filedesc, char*, int )   Constructs an fstream object that is associated with a filebuf object. The filebuf object is attached to an open file and to a specified reserve area.

    All fstream constructors construct a filebuf object. The first three use an internally allocated reserve area, but the fourth uses a user-allocated area. The user-allocated area is not automatically released during destruction.

    fstream::open

    void open( const char* szName, int nMode, int nProt = filebuf::openprot );

    Opens a disk file and attaches it to the stream’s filebuf object.

    Parameters

    szName

    The name of the file to be opened during construction.

    nMode

    An integer containing mode bits defined as ios enumerators that can be combined with the OR ( | ) operator. See the fstream constructor for a list of the enumerators. There is no default; a valid mode must be specified.

    nProt

    The file protection specification; defaults to the static integer filebuf::openprot. See the fstream constructor for a list of the other allowed values.

    Remarks

    If the filebuf object is already attached to an open file, or if a filebuf call fails, the ios::failbit is set. If the file is not found, then the ios::failbit is set only if the ios::nocreate mode was used.

    fstream::close

    void close();

    Remarks

    Calls the close member function for the associated filebuf object. This function, in turn, flushes any waiting output, closes the file, and disconnects the file from the filebuf object. The filebuf object is not destroyed.

    The stream’s error state is cleared unless the call to filebuf::close fails.

    < Example > (Employee_Record.cpp)

    /***

    //// Programmer : Mohammad Rastkar

    //// Capability : Implementing a variable sized record.

    //// Function   : User    -> can enter new records ( hourly or salaried ) and see them

                              (in separated sections).

                              Program -> saves recoeds in a file and show them later, in separate sections.

         Last Build : APR_3_08

    ***/

    /////////////     Includes    /////////////

     

    #include <cstdlib> // system()

    #include <conio.h> // getch()

    #include <fstream>

    #include <iostream>

    using namespace std;

     

     

    /////////////     Data types    /////////////

     

    enum TYPE { SALARIED = '0', HOURLY = '1' };

     

    struct Employee_Record // Employee record

    {

          char PAY_TYPE; // Tag_Field : SALARIED = '0', HOURLY = '1'

         

          union

          {

                struct // SALARIED

                {

                      double MONTHLY_RATE;

                      int    START_DATE;

                };

     

                struct // HOURLY

                {

                      double RATE_PER_HOUR;

                      int    REG_HOURS;

                      int    OVERTIME_HOURS;

                };

          };

     

          int  ID;

          int  AGE;

          char DEPT;

    } Employee;

     

     

    /////////////     Variable Declarations    /////////////

     

    char    choice; // for choice in menu

    fstream *fs; // file to save employee records

     

    /////////////     Main    /////////////

     

    int main()

    {

         

          while (1)

          {

                do  // menu

                {

                      system( "cls" ); // clear screen

                     

                      cout << "(1) Enter a new Record \n";

                      cout << "(2) Display Records \n";

                      cout << "(3) Exit \n\n";

                      cout << " Enter a choice (1-3) : ";

                      cin  >> choice;

                } while ( choice < '1' || choice > '3');

     

                switch ( choice )

                {

     

                case '1' : // Enter Records

     

                      system( "cls" );

     

                      cout << "\n\t\t < Entering a new record > ";

                      cout << "\n   Enter the following informations for the new record : ";

                      cout << "\n\n PAY_TYPE ( SALARIED : 0, HOURLY : 1 ) : ";

                      cin  >> Employee.PAY_TYPE;

     

                      cout << "\n ID : ";

                      cin  >> Employee.ID;

                      cout << "\n AGE : ";

                      cin  >> Employee.AGE;

                      cout << "\n DEPT (one character) : ";

                      cin  >> Employee.DEPT;

     

                      if ( Employee.PAY_TYPE == SALARIED )

                      {

                            cout << "\n MONTHLY_RATE : ";

                            cin  >> Employee.MONTHLY_RATE;

                            cout << "\n START_DATE : ";

                            cin  >> Employee.START_DATE;

                      }

     

                      if ( Employee.PAY_TYPE == HOURLY )

                      {

                            cout << "\n RATE_PER_HOUR : ";

                            cin  >> Employee.RATE_PER_HOUR;

                            cout << "\n REG_HOURS : ";

                            cin  >> Employee.REG_HOURS;

                            cout << "\n OVERTIME_HOURS : ";

                            cin  >> Employee.OVERTIME_HOURS;

                      }

     

                      fs = new fstream( "Employees.txt", ios::out | ios::app | ios::binary );

     

                      if (fs->fail())

                      {

                            cout << "\n Cann't open or create \"Employees\" file\n" << flush;

                            system( "pause" );

                            return 1;

                      }

     

     

                      fs->write( (char *) &Employee, sizeof(Employee) );

                     

                      fs->close();

                      delete fs;

                      fs = 0;

                     

                      break;

     

     

                case '2' : // Display Records

     

                      system( "cls" );

     

                      // Print Salaried records...

                      fs = new fstream( "Employees.txt", ios::in | ios::binary );

     

                      cout << "\n\t\t < Salaried >\n\n";

                      cout << "ID\tAGE\tDEPT\tMONTHLY_RATE\tSTART_DATE\n"

                             << "-------------------------------------------------- \n";

                     

                     

                      while (fs->read( (char *) &Employee, sizeof(Employee) ))

                      {

                            if ( Employee.PAY_TYPE == SALARIED )

                            {

                                  cout << Employee.ID << '\t';

                                  cout << Employee.AGE << '\t';

                                  cout << Employee.DEPT << '\t';

                                  cout << Employee.MONTHLY_RATE << "\t\t";

                                  cout << Employee.START_DATE   << '\n';

                            }

                      }

     

     

                      cout << "\n To see the Hourly records, " << flush;

                      system( "pause" );

     

                      // Print Hourly records...

                      system( "cls" );

     

     

                      fs->close();

                      delete fs;

                      fs = 0;

                     

                      fs = new fstream( "Employees.txt", ios::in | ios::binary );

                     

                      cout << "\n\t\t\t < Hourly > \n\n";

                      cout << "ID\tAGE\tDEPT\tRATE_PER_HOUR\tREG_HOURS\tOVERTIME_HOURS\n"

                             << "---------------------------------------------------------------------- \n";

     

     

                      while ( fs->read( (char *) &Employee, sizeof(Employee) ) )

                      {                      

                            if ( Employee.PAY_TYPE == HOURLY )

                            {

                                  cout << Employee.ID << '\t';

                                  cout << Employee.AGE << '\t';

                                  cout << Employee.DEPT << '\t';

                                  cout << Employee.RATE_PER_HOUR  << "\t\t";

                                  cout << Employee.REG_HOURS      << "\t\t";

                                  cout << Employee.OVERTIME_HOURS << '\n';

                            }

                      }

                     

                      cout << "\nTo see Menu, " << flush;

                      system( "pause" );

     

                      fs->close();

                      delete fs;

                      fs = 0;

     

                      break;

     

     

                case '3' :

                     

                      return 0;

     

                      break;

                }

               

          }

    }

    - I don't have Time To waste The Time!
    • Post Points: 20
  • 02-11-2007 11:45 AM In reply to

    • joan
    • Not Ranked
    • Joined on 01-16-2007
    • New Member
    • Points 50

    Re: Infos...

    Hello Mohammad Rastkar,

                                              Thanks a lot for your infors.  I want the .CPP file (add, delete, modify and list) due with Class instead of Structured.  Do you have?  Please e-mail to this e-mail address joancross2004@yahoo.com

    Thanks.

    Joan Choong

     

     

                        

    • Post Points: 10
  • 02-13-2007 1:44 PM In reply to

    Yes [Y] EMail Sent...

    Hello Joan Choong,
    I sent an email to you with the file attached (see more infos in your email Smiley Face [:)] ).
    - I don't have Time To waste The Time!
    • Post Points: 10
  • 02-05-2008 1:07 AM In reply to

    • hazof
    • Not Ranked
    • Joined on 02-05-2008
    • United States
    • New Member
    • Points 10

    Re: EMail Sent...

    Hello Mohammad Rastkar,

    I've been looking for ways to delete files by extension in a certain directory using C/C++, (e.g. *.txt) I made a program that creates a specific data file every time you use it. But I need to remove these files after I have collected the data.

    My first solution was to store the specific filenames into a single file then when I need to remove all the files, I have to recall the filenames string then one by one remove by commande remove(). But I dont think its practical.

     Please advise if you have better solutions, thanks! Appreciate it.

    Rgrds,

    Hazof

    • Post Points: 10
  • 02-05-2008 10:50 AM In reply to

    Yes [Y] Some Ways

    Hello Hazof,

    •  If you want, for example, delete all '.txt' files from 'c:\', you can use the following command :

    #include <cstdlib> // for system(), maybe including '<iostream>' with 'using namespace std;' be sufficient

    system( "del c:\\*.txt" ); // 'system()' will execute a command, (those you can run in 'CMD.exe')

    => With 'del' dos command, you have many options that's not in 'remove()', like : delete readonly files (by : 'del /F' )

    • Since you can execute any 'DOS command' with 'system()', then you can do many things! Here, you can make a directory, and create all of your files there, then delete that directory. The direct commands are :

    #include <direct.h> // for mkdir(), rmdir()

    mkdir( "c:\\my_tmp" ); // creates directory : when succeeds, return 0; for error, return -1

    rmdir( "c:\\my_tmp" ); // deletes a directory, return values are same as 'mkdir'

    => 'rmdir()' can only delete empty folders, but with the following command you are not limited! :

    system( "rd /Q /S c:\\my_tmp" ); // deletes 'my_tmp' folder, and all files and folders in it

    => Also, to delete all the files in a directory :

    system( "del /Q c:\\my_tmp" ); // using '/Q' switch to not confirming deletion of all files

    - I don't have Time To waste The Time!
    • Post Points: 5
  • 03-26-2008 7:47 AM In reply to

    Plese send me the cpp file

    Hello Mohammad Rastkar,

                                             Thanks a lot for ur post. I want the .CPP file (add, delete, modify and list) due with Class instead of Structured.  Do you have?  Please e-mail to this e-mail address chandrajithm@yahoo.com

    Thanks.

    CJ

     

    • Post Points: 10
  • 03-26-2008 6:02 PM In reply to

    Email [E] EMail Sent...

    Hello  chandrajith.m,

    I sent an email to you with the file attached.

    - I don't have Time To waste The Time!
    • Post Points: 5
  • 04-01-2008 2:14 PM In reply to

    • chong
    • Not Ranked
    • Joined on 01-22-2008
    • United Kingdom
    • Junior Member
    • Points 125

    Re: Infos...

    Hi Mohammad and guys

    You have shown a good program for demonstration.  I have compiled and run the program on my Windows XP computer.  I have noticed that, when the program takes an integer 26 as an input for AGE or ID, something funny happens.  Tr it!!  It may happen because my computer has got Winodws XP and VC++ 6.0.  I am not sure!!  If somebody can comment on it, I will be gratefull.  By the way, I fixed the problem by opening the data file in the binary mode(i.e  fs.open( "Employees", ios::in|ios::binary )).

     All the best

    Chong

    • Post Points: 10
  • 04-03-2008 8:19 PM In reply to

    Big Smile [:D] Amazing '26'! and Thanking Mr.chong!

    Hi All,

    => Thanks chong! your clue does the work!
    At this time, I have no idea why '26' is problematic when it's in 'text' mode, but 'binary' mode just solves that.

    I've changed and corrected the sample app (see in earlier posts in this thread), and now it's compatible with [VC++2005, on Vista] and [VC++6 on XP].

    - I don't have Time To waste The Time!
    • Post Points: 10
  • 04-10-2008 2:06 AM In reply to

    • paul trip
    • Not Ranked
    • Joined on 04-10-2008
    • United States
    • New Member
    • Points 10

    how to delete specific records from a binary file

    I am working on a binary file that will store various bits of information about customers (name, address, city, state, zip, balance, date of last payment, etc).  I can create and write to the file no problem, but I am not sure how to delete a specific record or search for a record and the modify it.  I am using a structure to store the data for each customer, which is working just fine.  Any help will be much appreciated.

    --Paul T 

    int getRandomNumber()
    {
    return 42; //was originally 4 determined by dice roll, but 42 is much better
    }
    • Post Points: 10
  • 04-11-2008 7:32 AM In reply to

    Idea [Idea] Can't Delete! But Update

    Hi paul trip,

    => Modify : you should first find the reacord position (by searching the file), then use 'seekp' function to change the file_pointer at the first of the record (if 'seekp()' doesn't work, just closing the file and reopening that may not put the file_pointer at the first of the file (even using 'clear' function), then you should use two 'fstream's or a pointer (fstream*) and delete that, then create a new one, then use 'seekp()'). When the file_pointer was at the first of the record, then write the new info(struct) to the file (it will replace old info with new one).

    => Delete : There is no method to delete from a file, then you should do that by writing whole of file in a new file, without deleted record(s) (you can first specify deleted ones (when deleting) with a change in the record (e.g. set the ID to 0 (if no one has ID of 0)), then later, really delete records by creating a new file).

    => Also : There is an approach using class 'string', that is used as an example in this code sample :

    [C++] Simple Multiplication Test - Involves with : files & strings & arrays & ...

    It has this advantages : speed (just two file interactions), flexibility (using all of 'class string' methods), simplicity (less codes), ...

    but just you can't use structs explicitly (you should use each field separately).

    - I don't have Time To waste The Time!
    • Post Points: 10
  • 06-15-2008 4:20 PM In reply to

    • onglim
    • Not Ranked
    • Joined on 06-15-2008
    • Malaysia
    • New Member
    • Points 20

    Please send the me the cpp file. Thanks.

     

    Hello Mohammad Rastkar,

    Thanks a lot for ur post. I want the .CPP file (add, delete, modify and list) due with Class instead of Structured. Do you have? Please e-mail to this e-mail address onglim1987@hotmail.com

    I try to download from -> Filed under:   but the page not found.

    Thanks.

    OL

    • Post Points: 10
Page 1 of 2 (16 items) 1 2 Next >