Solved

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

Posted on 2002-05-30
2
242 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
ID: 7046149
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
ID: 7046228
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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article will show you some of the more useful Standard Template Library (STL) algorithms through the use of working examples.  You will learn about how these algorithms fit into the STL architecture, how they work with STL containers, and why t…
IntroductionThis article is the second in a three part article series on the Visual Studio 2008 Debugger.  It provides tips in setting and using breakpoints. If not familiar with this debugger, you can find a basic introduction in the EE article loc…
The goal of the tutorial is to teach the user how to use functions in C++. The video will cover how to define functions, how to call functions and how to create functions prototypes. Microsoft Visual C++ 2010 Express will be used as a text editor an…
The goal of the video will be to teach the user the concept of local variables and scope. An example of a locally defined variable will be given as well as an explanation of what scope is in C++. The local variable and concept of scope will be relat…

920 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

16 Experts available now in Live!

Get 1:1 Help Now