这基本上是我用来存储整个文件的代码的一部分,并且运行良好......但是当我试图存储一个大于 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/