无法将整数写入二进制文件C ++

时间:2012-11-04 13:41:48

标签: c++ file-io binary

这基本上是我用来存储整个文件的代码的一部分,并且运行良好...但是当我尝试存储大于120的整数或者类似的东西时,程序写入看起来像一堆垃圾而不是我想要的整数。有小费吗 ?我是一名大学生,并没有发现什么事情。

    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);

我已经检查了atoi部分,它确实返回了我想写的数字。

2 个答案:

答案 0 :(得分:2)

我更改并添加了一些代码,它运行正常:

#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);
}

确保使用正确的参数打开文件,并且为atoi(str)指定的字符串是正确的。

输入数字1013后,我使用十六进制编辑器检查了二进制文件。

答案 1 :(得分:1)

int i = atoi("123");
std::ofstream file("filename", std::ios::bin);
file.write(reinterpret_cast<char*>(&i), sizeof(i));
  • 请勿在此使用指针。
  • 从不在C ++中使用malloc / free
  • 使用C ++文件流,而不是C流。
相关问题