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++ - 无法将 LIBEVENT 链接为 C++

c# - 读取和写入文件C#时共享冲突IOException

linux - 二进制文件中的 .bash_history

algorithm - 查找小于或等于 n 且其二进制表示中没有连续 '1' 的正整数的数量

c - 二进制添加大型字符数组?

c++ - 为什么以下代码会使我的计算机发出蜂鸣声?

c++ - 是否可以使用宏来创建 typedef?

创建文件作为系统

php取消链接。不返回任何错误消息并且不删除我的文件