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

标签 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 部分,它确实返回了我想要写入的数字。

最佳答案

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

#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 后,我使用十六进制编辑器检查了二进制文件。

关于c++ - 无法将整数写入二进制文件 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13219040/

相关文章:

c++ - c++如何初始化一个对象?以下案例是否做了两次?

c++ - 使用 openMPI 发送对象

c++ - 模板类和可能的性能问题

c++ - QT 应用程序 - 替换嵌入式资源

ios - 将 String 转换为二进制时缺少一位

c++ - 尝试用值初始化列表但在我使用变量创建大小时不起作用

c++ - fstream 代码没有在我的桌面上创建文件

java - 使用 String.split 时,我不断收到 "ArrayIndexOutOfBounds"异常

c - 从文件循环读取 - 无法使用 feof 或 getc 进入循环

math - 如何查找具有以下约束的二进制数的个数: