简体   繁体   English

读取包含无符号整数的文件,并将其写入C ++中的二进制文件

[英]Read a file containing unsigned ints and write it into binary in C++

I have a text file containing unsigned integers in the range 0,..,2^32-1. 我有一个文本文件,其中包含0,..,2 ^ 32-1范围内的无符号整数。 Each line contains a single integer (and a newline char). 每行包含一个整数(和换行符)。

I want to write it into a binary file to save space (such that each int will take exactly 4 bytes). 我想将其写入二进制文件以节省空间(这样每个int都会占用4个字节)。 What'd be the best way to do that? 最好的方法是什么?

I've tried a few options, none of them seems to work. 我尝试了几种选择,但似乎都没有用。 Help will be appreciated. 帮助将不胜感激。

Current (non working) code: 当前(无效)代码:

#include <fstream>
#include <iostream>
#include <stdio.h>

int main(){
    int x;
    while (std::cin >> x){
        fwrite((void*)&x, sizeof(x), 1, stdout);
    }
    return 0;
}

It is compiled using: g++ compress.cc -o compress . 它使用以下命令编译: g++ compress.cc -o compress

However, it seems to only output the first integer. 但是,似乎只输出第一个整数。

For example, have the I ran the command ./compress < bla | wc -c 例如,让我运行命令./compress < bla | wc -c ./compress < bla | wc -c

Where "bla" is a file containing 其中“ bla”是包含以下内容的文件

1864754174
2150244390
1703231727

The result of the command was 4 , and not 12 as I expected. 命令的结果是4 ,而不是我期望的12

your problem is that you are trying to write int instead of unsigned int. 您的问题是您试图写int而不是unsigned int。 the diffrence between those 2 isnt the size of them but the use of the bytes. 这两个之间的差异不是它们的大小,而是字节的使用。

in unsigned int every bit reprsent 2^(index -1) index starting from 1. in unsigned int每一位代表从1开始的2 ^(index -1)索引。

in int the bits are used like unsiged int just the last bit is used to reprsent the sign of the number and beacuse of that you can represent smaller numbers. 在int中,这些位的使用方式与未在int中使用的int一样,只是最后一位用于表示该数字的符号,因为它可以表示较小的数字。

If I understood you correctly, you want to read from a text file containing uints and write those into a binary file. 如果我对您的理解正确,则希望从包含uint的文本文件中读取并将其写入二进制文件。 Reading: 读:

std::vector<unsigned int> readUints(const std::string& filepath){
    std::vector<unsigned int> numbers;
    std::ifstream file(filepath);
    if(!file.is_open()){
        //Handle file not found
    }
    unsigned int number = 0;
    while(file >> number){
        numbers.push_back(number);
    }
    return numbers;

Writing: 写作:

void writeUints(const std::vector<unsigned int>& numbers, const std::string& filepath){
    std::ofstream file(filepath, ios_base::binary | ios_base::out);
    if(!file.is_open()){
        //Handle file not found
    }
    for(int i = 0; i < numbers.size(); i++){
        file.write(reinterpret_cast<char*>(&numbers[i], 4);
    }
}

Make sure to include <fstream> . 确保包括<fstream> You can change unsigned int to uint32_t to make sure it is exactly 32 bits wide on every platform 您可以将unsigned int更改为uint32_t ,以确保每个平台上的宽度恰好为32位

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

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