在c ++中读取和写入二进制文件的int [英] Reading and writing int to a binary file in c++
问题描述
我不清楚如何读取长整数工作。如果我说
I am unclear about how reading long integers work. If I say
long int a[1]={666666}
ofstream o("ex",ios::binary);
o.write((char*)a,sizeof(a));
将值存储到文件,并想要读取它们
to store values to a file and want to read them back as it is
long int stor[1];
ifstream i("ex",ios::binary);
i.read((char*)stor,sizeof(stor));
如何使用存储在多个字节字符中的信息显示相同的数字数组?
how will I be able to display the same number as stored using the information stored in multiple bytes of character array?
推荐答案
o.write
不写入字符,如果标记为ios :: binary)。使用char指针是因为char的长度为1个字节。
o.write
does not write character, it writes bytes (if flagged with ios::binary). The char-pointer is used because a char has length 1 Byte.
o.write((char*)a,sizeof(a));
(char *)a
的 o.write
应该写。然后将 sizeof(a)
字节写入文件。没有字符存储,只是字节。
(char*) a
is the adress of what o.write
should write. Then it writes sizeof(a)
bytes to a file. There are no characters stored, just bytes.
如果你在一个十六进制编辑器中打开文件,你会看到这样的如果a int i = 10
:
0A 00 00 00
(4字节,x64上)。
If you open the file in a Hex-Editor you would see something like this if a is int i = 10
:
0A 00 00 00
(4 Byte, on x64).
阅读是类比。
这是一个工作示例:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main (int argc, char* argv[]){
const char* FILENAM = "a.txt";
int toStore = 10;
ofstream o(FILENAM,ios::binary);
o.write((char*)&toStore,sizeof(toStore));
o.close();
int toRestore=0;
ifstream i(FILENAM,ios::binary);
i.read((char*)&toRestore,sizeof(toRestore));
cout << toRestore << endl;
return 0;
}
这篇关于在c ++中读取和写入二进制文件的int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!