Improve company productivity with a Business Account.Sign Up

x
?
Solved

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

Posted on 2002-05-30
2
Medium Priority
?
290 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 23

Accepted Solution

by:
ambience earned 400 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

Get your problem seen by more experts

Be seen. Boost your question’s priority for more expert views and faster solutions

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

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…
Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
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…
The goal of the video will be to teach the user the difference and consequence of passing data by value vs passing data by reference in C++. An example of passing data by value as well as an example of passing data by reference will be be given. Bot…

595 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