Link to home
Start Free TrialLog in
Avatar of Hsiang2k
Hsiang2k

asked on

Help!!!!!Problem with creating binary file.

I have a problem.I want to create a binary file and write to it.I have this code:
CFile f;
     CFileException e;
if (f.Open(FullPath, CFile::modeCreate | CFile::typeBinary | CFile::modeWrite , &e))
               {
                    //f.WriteString(m_password);
                    //f.WriteString("\n");
                    f.Write("test",4);

                    f.Close();
               }
But when i run this programm and open bin file with notepad i see usual text file.What i do wrong?
This file is supposed to contain password and i want the file to contain weird characters when somebody open it with Notepad.
Thank to everybody.
ASKER CERTIFIED SOLUTION
Avatar of ambience
ambience
Flag of Pakistan image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Another method of writing binary file which uses stdio.h.


///////////////////////////////////////////////
// COPYRIGHT          : LOH HON CHUN         //
///////////////////////////////////////////////

// binaryfile.cpp
// demonstrates how to use binary files for reading and writing

// include necessary pre-defined header files
#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

// structure for employee record
typedef struct EMPDATA
{
      int number;
      char name[16];
      char sex;
      int salary;
} EMPDATA;

// function prototypes
int draw_menu(void);
void err_msg(int type);
int read_record(void);
int write_record(void);

// main program entry point
int main(void)
{
      int option_selected=0;
      int exit_status=0;

      // exit program if user chooses to exit or file opening in binary mode fails
      while ( option_selected != 3 && exit_status != 1 )
      {
            // get input from user to read or write records
            option_selected = draw_menu();

            // if user chooses to read record
            if ( option_selected == 1 )
            {
                  exit_status = read_record();
            }
            // if user chooses to write record
            else if ( option_selected == 2 )
            {
                  exit_status = write_record();
            }
      }

      return exit_status;
}

// draw the main menu and return the an integer to indicate the option selected by user
int draw_menu(void)
{
      char option_selected;

      // read input
      while ( true )
      {
            system("cls");

            // draw the menu
            puts("1. Read record");
            puts("2. Write record");
            puts("3. Exit");
            printf("Enter your choice > ");
            fflush(stdin);

            // read input
            option_selected = getchar();

            if ( option_selected == '1' || option_selected == '2' ||
                   option_selected == '3'
               )
            {
                  break;
            }
            else
            {
                  puts("\n>> Invalid option!");
                  printf("Press <ENTER> to continue ");
                  fflush(stdin);
                  getchar();
            }
      }

      // minus 48 to obtain either 1, 2, or 3
      return (option_selected - 48);
}

// display an error message dialog box
void err_msg(int type)
{
      switch ( type )
      {
            case 1 :// formatted message box for error message
                  MessageBox(NULL,
                                 "Fatal Error: There are no records to read\n"\
                                 "             Application terminated",
                                 "Fatal Error",
                                 MB_OK|MB_ICONERROR
                                );
                  break;
            case 2 :// formatted message box for error message
                  MessageBox(NULL,
                                 "Fatal Error: Error opening file in binary mode\n"\
                                 "             Application terminated",
                                 "Fatal Error",
                                 MB_OK|MB_ICONERROR
                                );
                  break;
      }
}

// reads record from file
int read_record(void)
{
      int count=0;
      int num_record;
      EMPDATA empdata[1];
      FILE *fp;

      system("cls");

      // if file opening in binary mode fails
      if ( (fp = fopen("data.dat", "rb")) == NULL )
      {
            err_msg(1);

            // 1: EXIT_FAILURE
            return 1;
      }
      // if file opening in binary mode is successful
      else
      {
                                    ///////////////////////
                                    ///       NOTE      ///
                                    ///////////////////////
            ///////////////////////////////////////////////////
            // THE FIRST METHOD IS THE BETTER METHOD TO USE //
            ///////////////////////////////////////////////////


            /////////////////////////////////////
            // begining of ALTERNATIVE BLOCK 1 //
            /////////////////////////////////////
            fseek(fp, 0, SEEK_END);
            num_record = int(ftell(fp)) / (sizeof(EMPDATA));
            fseek(fp, 0, SEEK_SET);
            fread(empdata, sizeof(empdata), 1, fp);

            while ( num_record-- )
            ////////////////////////////////
            // end of ALTERNATIVE BLOCK 1 //
            ////////////////////////////////

            /////////////////////////////////////
            // begining of ALTERNATIVE BLOCK 2 //
            /////////////////////////////////////
            while ( !(feof(fp)) )
            ////////////////////////////////
            // end of ALTERNATIVE BLOCK 2 //
            ////////////////////////////////
            {
                  // print records
                  printf(">> Retrieving record %d\n", ++count);
                  Sleep(250);
                  printf("   >File position marker = %ld\n\n", ftell(fp));
                  Sleep(100);
                  printf("    Employee number: %02d\n", empdata[0].number);
                  Sleep(100);
                  printf("    Employee name  : %s\n", empdata[0].name);
                  Sleep(100);
                  printf("    Employee sex   : %c\n", empdata[0].sex);
                  Sleep(100);
                  printf("    Employee salary: %d\n\n", empdata[0].salary);

                  printf("Press <ENTER> to continue......");
                  fflush(stdin);
                  getchar();
                  printf("\n");

                  // read next record
                  fread(empdata, sizeof(empdata), 1, fp);
            }

            // close file pointer
            fclose(fp);

            // 0: EXIT_SUCCESS
            return 0;
      }
}

// write records onto file
int write_record(void)
{
      int count;
      long file_position;
      char tocontinue='y';
      EMPDATA empdata[1];
      FILE *fp;

      system("cls");

      // if file opening in binary mode fails or creation of file fails in the case
      // if file does not exits in the first place
      if ( (fp = fopen("data.dat", "ab")) == NULL )
      {
            err_msg(2);

            // 1: EXIT_FAILURE
            return 1;
      }
      // if file opening in binary mode is successful
      else
      {
            fseek(fp, 0, SEEK_END);
            file_position = ftell(fp);
            count = int(file_position) / sizeof(empdata);
            printf("There are %d existing records in database.\n", count);

            while ( tocontinue == 'y' )
            {
                  printf(">> Enter fields for record %d\n", ++count);
                  empdata[0].number = count;
                  printf("   >Enter employee's name : ");
                  fflush(stdin);
                  gets(empdata[0].name);
                  while ( true )
                  {
                        printf("   >Enter employee's sex: ");
                        fflush(stdin);
                        empdata[0].sex = toupper(getchar());
                        // if user enters an invalid sex
                        if ( empdata[0].sex != 'M' && empdata[0].sex != 'F' )
                              printf("    Invalid sex!\n");
                        // if user enters a valid sex
                        else
                              break;
                  }
                  while ( true )
                  {
                        printf("   >Enter employee's salary: ");
                        fflush(stdin);
                        // user do not enter an integer for salary
                        if ( scanf("%d", &empdata[0].salary) == 0 )
                        {
                              printf("    Invalid salary!\n");
                        }
                        // if user enters an integer for salary
                        else
                        {
                              break;
                        }
                  }

                  // write record into binary file
                  fwrite(empdata, sizeof(empdata), 1, fp);

                  // prompt user whether to continue entering next record
                  do
                  {
                        printf("\n>> Enter next record (y/n)? ");
                        fflush(stdin);
                        tocontinue = tolower(getchar());
                        if ( tocontinue != 'y' && tocontinue != 'n' )
                              printf("   Invalid input");

                  } while ( tocontinue != 'y' && tocontinue != 'n' );
            }

            // close file pointer
            fclose(fp);

            // 0: EXIT_SUCCESS
            return 0;
      }
}


hongjun