Solved

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

Posted on 2002-05-30
2
229 Views
Last Modified: 2010-04-02
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.
0
Comment
Question by:Hsiang2k
2 Comments
 
LVL 22

Accepted Solution

by:
ambience earned 100 total points
Comment Utility
well if you write ASCII you will see ascii, and this is the only thing wrong.

There can be numerous schemes for encrypting passwords,heres a simple way that would give you a *binary* feeling

if (f.Open(FullPath, CFile::modeCreate | CFile::typeBinary | CFile::modeWrite , &e))
{
     for(int i=0; i<m_password.GetLength(); i++)
     {
        TCHAR ch = m_password[i];
        ch = _T('0') - ch;  // subtract ASCII 0 to make it binary
        f.Write(&ch , 1);
     }  
                   //f.WriteString(m_password);

      f.Close();
}

offcourse when you read it you have to add _T('0') also

there is also another way that uses XOR

TCHAR ch = m_password[i] ^ 67;  // XOR inverts some bits
f.Write(&ch , 1);

when reading XOR with 67 again to get the real value back

hope this gives you a start
0
 
LVL 33

Expert Comment

by:hongjun
Comment Utility
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
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

What is C++ STL?: STL stands for Standard Template Library and is a part of standard C++ libraries. It contains many useful data structures (containers) and algorithms, which can spare you a lot of the time. Today we will look at the STL Vector. …
Many modern programming languages support the concept of a property -- a class member that combines characteristics of both a data member and a method.  These are sometimes called "smart fields" because you can add logic that is applied automaticall…
The viewer will learn how to pass data into a function in C++. This is one step further in using functions. Instead of only printing text onto the console, the function will be able to perform calculations with argumentents given by the user.
The viewer will learn how to clear a vector as well as how to detect empty vectors in C++.

743 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

18 Experts available now in Live!

Get 1:1 Help Now