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

  • 14 years ago

    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

     

     

  • 14 years ago
    • 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 ?)
  • 14 years ago

    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

  • 14 years ago

    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.

  • 14 years ago

    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 [email protected]

    Thanks.

    Joan Choong

     

     

                        

  • 14 years ago
    Hello Joan Choong,
    I sent an email to you with the file attached (see more infos in your email Smiley Face [:)] ).
  • 13 years ago

    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

  • 12 years ago

    Hello  chandrajith.m,

    I sent an email to you with the file attached.

  • 12 years ago

    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

  • 12 years ago

    Hi chong & All,

    => Thanks chong ! your clue does the work! 'binary' mode just solves that. I've changed and corrected the sample program (see in 4th post in this thread to download or view that).

     =>  I think the answer of 'why 26 is problematic?' is :

    When you're writing a structure in a file, despite of file mode(binary or text), it will be written in binary format, then when you want to read from that file later, if you read in binary mode, there is no problem, but if you want to read in text mode, and if previously you wrote '26' as an integer member of a structure in the file, now when you want to read structure from the file, when 'read()' wants to read integer member, it doesn't read '26' as an integer, it reads '^Z' (Ctrl+Z) since it's in binary format, and '^Z' means end of input, then it stops reading. Then actually you have nothing from file! Why '26' means '^Z'? see MSDN 'ASCII Character Codes' section(or see ASCII codes from any other resources), then you'll see(in 'Chart 1') that '26' is the ASCII code of '^Z'.

    Then never read a binary file in text mode, unless you really intend that! Wink

  • 12 years ago

    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).

  • 12 years ago

    Hi onglim,

    => Here is a code sample that your desired info is in this section of code sample : '3. Class_List_Manipulation.cpp' (this is your requested file that you can download it in '4.  Download Files' section of code sample)

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

    => If you want 'Employee_Record.cpp', get the download link from 4th post in this thread.

  • 12 years ago

    Hi  lille,

    => Please first see the 14th post in this thread and also download 'Employee_Record.cpp' (get the link from the 4th post) and have a look at that. Then if you have further questions just ask them Wink.

    => For OOP concept, it depends on your program and how you want to implement that, but in general, you should define a main class(there is maybe some inherited classes) for all of file interactions, like 'fstream' in C++ or 'CFile' in MFC or 'File' in C#. Then add specific methods that your program demands and some optional utility functions to help other methods and some optional general(for all programs) methods to use on demand. Always keep your methods' signature(prototype) more general, then you can use your class and its methods in other programs too, without recoding.

    My code sample (Employee_Record.cpp) aims to show how to interact with files, then it's not using classes, just little utility functions, but you can use the code for your methods easily.

  • 12 years ago
    It is just brilliant stuff. Well done Mohammad. Best regards Chong

  • 12 years ago

     Thank you Chong for all of your helps and attentions, without them, I couldn't do like this! Wink

  • 12 years ago

    My dear friend Mohammad,

    The pleasure is mine!!  You have helped me with a geat deal more.  Thanks.

    Best regards

    Chong

    PS.

    Have you got any idea about the question I asked about how to disable the other 'Save as"  menu item in the word processor?  I would love to know how to!

Post a reply

Enter your message below

Sign in or Join us (it's free).

Contribute

Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“The trouble with programmers is that you can never tell what a programmer is doing until it's too late.” - Seymour Cray