user1270116
user1270116

Reputation: 11

Can't write an integer into a binary file C++

This is basically the part of the code that i used to store the entire file, and works well ... but when i tryed to store a integer bigger than 120 or something like that the program writes seems like a bunch of trash and not the integer that i want. Any tips ? I am an college student and dont have a clue whats happening.

    int* temp

    temp = (int*) malloc (sizeof(int));

    *temp = atoi( it->valor[i].c_str() );

    //Writes the integer in 4 bytes
    fwrite(temp, sizeof (int), 1, arq);

    if( ferror(arq) ){
      printf("\n\n Error \n\n");
      exit(1);
    }

    free(temp);

I've already checked the atoi part and it really returns the number that I want to write.

Upvotes: 0

Views: 911

Answers (2)

Konrad Rudolph
Konrad Rudolph

Reputation: 545588

int i = atoi("123");
std::ofstream file("filename", std::ios::bin);
file.write(reinterpret_cast<char*>(&i), sizeof(i));
  • Do not use pointers here.
  • Never use malloc / free in C++.
  • Use C++ file streams, not C streams.

Upvotes: 1

Roy Spector
Roy Spector

Reputation: 151

I changed and added some code and it works fine:

#include <iostream>

using namespace std;

int main()
{

    int* temp;
    FILE *file;
    file = fopen("file.bin" , "rb+"); // Opening the file using rb+ for writing
                                      // and reading binary data
    temp = (int*) malloc (sizeof(int));

    *temp = atoi( "1013" );           // replace "1013" with your string

    //Writes the integer in 4 bytes
    fwrite(temp, sizeof (int), 1, file);

    if( ferror(file) ){
      printf("\n\n Error \n\n");
      exit(1);
    }

    free(temp);
}

Make sure you are opening the file with the correct parameters, and that the string you give to atoi(str) is correct.

I checked the binary file using hex editor, after inputting the number 1013.

Upvotes: 2

Related Questions