简体   繁体   English

在 C++ 中从/向二进制文件读取和写入整数

[英]Reading and writing integers from/to a binary file in C++

The trying to write a simple program that would write integers value into a file, then read and display the integers in the order it was written.尝试编写一个简单的程序,将整数值写入文件,然后按照写入的顺序读取和显示整数。 The integers written into the file are {0,2,....18}.写入文件的整数为 {0,2,....18}。 The following is the code:以下是代码:

// Example program
#include <iostream>
#include <string>
#include <sstream>
#include <stdlib.h>
#include <stdio.h>
#include <fstream>
using namespace std;

int main()
{
    typedef unsigned int uint32_t;
    // Write to file
    std::ofstream osObj;
    string filename = "testFile";
    osObj.open(filename.c_str(), std::ofstream::binary);

    for (uint32_t i=0; i<10; ++i)
    {
        uint32_t a = i*2;
        osObj.write(reinterpret_cast<const char *>(&a), sizeof(a));
        //osObj.write((char *)(&a), sizeof(a));
    }

    //read from file
    std::ifstream isObj;
    isObj.open(filename.c_str(), std::ofstream::binary);
    if (isObj.fail()) { cout<<"Failed to open file"<<endl; }

    for (uint32_t i=0; i<10; ++i)
    {
        char val[sizeof(uint32_t)];
        isObj.read(val, sizeof(val));
        uint32_t* valUint = reinterpret_cast<uint32_t *>(val);
        cout<<*(valUint)<<endl;
    }
    return 0;
}

This doesn't produce the expected result.这不会产生预期的结果。 I'm getting the following output:我得到以下输出:

62586880
62586880
62586880
62586880
62586880
62586880
62586880
62586880
62586880
62586880

The byte ordering is little-endian.字节顺序是小端。 What am I missing?我错过了什么?

You shouldn't add i to valUint .您不应该将i添加到valUint You're only reading one integer into val , so the integer you just read is at the address pointed to by valUint .您只是将一个整数读入val ,因此您刚刚读取的整数位于valUint指向的地址valUint It's not an array of integers, so there's no reason to index the pointer.它不是整数数组,因此没有理由索引指针。

    cout<< *valUint << endl;

A simpler way to write it is:更简单的写法是:

for (unint32_t i = 0; i < 10; ++i) {
    uint32_t val;
    isObj.read(reinterpret_cast<char *>&val, sizeof val);
    cout << val << endl;
}

Also, you should do osObj.close() at the end of the writing loop.此外,您应该在写入循环结束时执行osObj.close() The file is buffered, and the buffer may not have been flushed.该文件已缓冲,并且缓冲区可能尚未刷新。 If you checked for errors when reading, you probably would have noticed that nothing was being read from the file.如果您在阅读时检查错误,您可能会注意到没有从文件中读取任何内容。

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

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