Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6761549
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 26, 20262026-05-26T14:12:23+00:00 2026-05-26T14:12:23+00:00

I created a read / write of bytes into a binary file using fstream

  • 0

I created a read / write of bytes into a binary file using fstream object

#include <iostream>
#include <fstream>

using namespace std;

#define COL_WIDTH 20

int writeBinaryFile(char *desPath);
int readBinaryFile(char *desPath);

int age;
char name[COL_WIDTH];
int recsize = sizeof(int)+sizeof(name);
int n;

int main(){

    char desPath[MAX_PATH+1];
    char input[2];

    while(true){
        cout  << "Main Menu:\n1 Write Binary File\n2 Read Binary File\n3 EXIT" << endl;
        cin.getline(input, 2);          


        if(atoi(input)== 1){
            cout << "Enter destination path:" << endl;
            cin.getline(desPath, MAX_PATH+1);
            for(;;){
                int output = writeBinaryFile(desPath);
                if(output == 1) break;
                else if(output == 2) { *input = '4'; break;}
            }
        }
        else if(atoi(input) == 2){
            cout << "Enter destination path:" << endl;
            cin.getline(desPath, MAX_PATH+1);
            for(;;){
                int output = readBinaryFile(desPath);
                if(output == 1) break;
                else if(output == 2){ *input = '4'; break;}
            }
        }

        else if(atoi(input) == 3)
            break;
        else cout << "You entered wrong input, enter only 1 or 2." << endl;

        if(atoi(input) == 4) continue;
        else break;

    }

    system("pause");
    return 0;   
}

int writeBinaryFile(char *desPath){
    char option[2];
    fstream wBin(desPath, ios::binary | ios::out);
    if(!wBin){
        cout << desPath << " is not good path."<< endl;
        return 1;
    }
    cout << "Enter name: " << endl;
    cin.getline(name,COL_WIDTH);
    cout << "Enter age: " << endl;
    cin >> age;

    cout << "Enter record number: " << endl;
    cin >> n;

    wBin.seekp(n*recsize); 
    wBin.write(name, sizeof(name));
    wBin.write((char*)&age, sizeof(age));
    wBin.close();

    cout << "Enter record again? Press:" << endl
         << "Enter to continue" << endl
         << "Q to quit" << endl
         << "M to go back to main menu" << endl;

    cin.ignore(256,'\n');
    cin.getline(option,2);

    if(option[0] == 'q' ||option[0] == 'Q') return 1;
    else if(option[0] == 'm' ||option[0] == 'M') return 2;

    return 0;
}


int readBinaryFile(char *desPath){       
    char option[2];
    fstream rBin(desPath, ios:: binary | ios:: in);
    if(! rBin){
        cout << "File not found!" << endl;
        return 1;
    }
    cout << "What record number?" <<endl;
    cin >> n;
    rBin.seekp((n*recsize));
    rBin.read(name,sizeof(name));
    rBin.read((char*)&age, sizeof(int));


    cout << name <<endl;
    cout << age << endl;
    rBin.close();
    cout << "Print more? Press enter. Press Q to QUIT or M to go back." << endl;
    cin.clear();
    cin.sync();
    cin.getline(option, 2);

    if(option[0] == 'q'|| option[0] == 'Q'){rBin.close(); return 1;}
    else if(option[0] == 'm' || option[0] == 'M'){rBin.close(); return 2;}

    return 0;
}

i created a binary file first with name, age, recordnumber ( position of bytes which is 0) then on second loop i input name, age, recordnumber 2.
When i tried to read the first pair(char*, int) of bytes pos(0) but it returns wrong result but when i tried to read the last pair in pos(1) it returns correct result.

I also tried making 3 times the input, but only the last char* and int is correct.

Why is it getting wrong results in first bytes(name(20bytes),age(4bytes)) but getting correct it last bytes?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-26T14:12:23+00:00Added an answer on May 26, 2026 at 2:12 pm

    In each call to writeBinaryFile the output is reopened, destroying the previous contents of the file.

    You’ll want to use ios::binary | ios::ate | ios::out | ios::in.

    But, this bitmask will not create the file if it does not exist. You can work around that problem with this code sequence:

    int writeBinaryFile(char *desPath) {
      ...
      // Create the file only if it doesn't exist
      fstream(desPath, ios::binary|ios::out|ios::app);
    
      // Now it exists -- open it
      fstream wBin(desPath, ios::binary|ios::out|ios::in);
      ...
    }
    

    Credit @JoeFish for the useful part of the answer.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

i'm trying to read a binary file (for example an executable) into a string,
I'm using the following code to create a file and write data into it:
I am working with Delphi Prism and creating and writing into binary file using
I created a SQLite database on Android device. The program can read/write to database
I'm using Python 2.x [not negotiable] to read XML documents [created by others] that
I'm trying to read a binary file (which represents a matrix in Matlab) in
I want to be able to read and write a large file in parallel,
How do I read a raw byte array from any file... Dim bytes() as
I have a text file which was created using some Microsoft reporting tool. The
I created a fifo pipe $ mkfifo pipename Now if I write somthing into

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.