简体   繁体   English

在C ++中读取和写入二进制文件

[英]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 does not write character, it writes bytes (if flagged with ios::binary). o.write不写字符,它写入字节(如果用ios :: binary标记)。 The char-pointer is used because a char has length 1 Byte. 使用char指针是因为char的长度为1 Byte。

o.write((char*)a,sizeof(a)); 

(char*) a is the adress of what o.write should write. (char*) ao.write应该写的地址。 Then it writes sizeof(a) bytes to a file. 然后它将sizeof(a)字节写入文件。 There are no characters stored, just bytes. 没有存储字符,只有字节。

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). 如果你在十六进制编辑器中打开文件,你会看到类似这样的东西,如果a是int i = 100A 00 00 00 (4字节,在x64上)。

Reading is analogue. 阅读是模拟的。

Here is a working example: 这是一个工作示例:

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

Sorry I took so long to see your question. 对不起,我花了很长时间才看到你的问题。

I think the difference between binary is the binary will read and write the file as is. 我认为二进制文件的区别在于二进制文件将按原样读写文件。 But the non-binary (ie text) mode will fix up the end-of-line '\\n' with carriage-return '\\r'. 但是非二进制(即文本)模式将使用回车符'\\ _'来修复行尾“\\ n”。 The fix-up will change back and forth between '\\n' and '\\r', or "\\n\\r" or "\\r\\n" or leave it as '\\n'. 修复将在'\\ n'和'\\ r'之间或“\\ n \\ r”或“\\ r \\ n”之间来回切换,或将其保留为'\\ n'。 What it does depends on whether the target operating system is Mac, Windows, Unix, etc. 它的作用取决于目标操作系统是Mac,Windows,Unix等。

I think if you are reading and writing an integer, it will read and write your integer fine and it will look correct. 我想如果你正在读写一个整数,它会读取和写出你的整数,它看起来是正确的。 But if some byte(s) of the integer look like '\\r' and '\\n', then the integer will not read back correctly from the file. 但是如果整数的某些字节看起来像'\\ r'和'\\ n',则整数将无法从文件中正确读回。

Binary assures that reading back an int will always be correct. 二进制确保读回int总是正确的。 But you want text mode to format a file to be read in a text editor such as Windows's Notepad. 但是,您希望文本模式格式化要在文本编辑器(如Windows的记事本)中读取的文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM