用C ++读写二进制文件 [英] Reading and writing binary files in C++
问题描述
我对C ++还是陌生的,从昨天开始只有几个小时的自学时间. 因此:
I am entirely new to C++ with just a couple of hours self-teaching, that started yesterday. SO:
我有一个未压缩的简单beep.wav
文件,大约只有3秒钟长,并且只有一个蜂鸣声.
I have a uncompressed simple beep.wav
file, just about 3 seconds long with a single beeping sound in it.
我最终想要实现的是,仅读取文件,同时写入二进制数据,所有数据包括:标头, ftm 和 data 或所有十六进制可读数据,并将其转储到简单的beep.txt
文件中.
What I am ultimately trying to achieve is, just to read the file, and at the same time write the binary data, all including: the header, ftm and data or all that is hex readable data and dump it into a simple beep.txt
file.
在C ++中有可能吗?如果是这样,我应该如何开始读取和转储二进制文件?
使用<fstream>
类
#include <iostream>
#include <fstream>
int main()
{
ifstream myfile ("beep.wav", ios::in|ios::binary|ios::ate);
if (myfile.is_open())
{
//reading goes here
}
return 0;
}
推荐答案
如yzt
所述,您需要提前了解.wav
中的内容和顺序.据我所知,您将获得标签,标头和值(样本)以及压缩信息.因此,首先开始:
As mentioned by yzt
, you need to know by advance what's in your .wav
and in which order. As far as I know, you will have tags, headers and values (samples) as well as compression informations. So, to give a start :
例如,如果您知道第一件事就是读取压缩率,则可以通过提取开始压缩过程,该过程可能是double
:
If you know, by example, that the very first thing to do is to read the compression rate, you'll start your reading process by extracting may be a double
:
ifstream myfile("beep.wav", ios::in|ios::binary);
double compression_rate;
myfile.read((char*)&compression_rate, sizeof(compression_rate));
// As well as probably the sample rate...
double sample_rate;
myfile.read((char*)&sample_rate, sizeof(sample_rate));
然后是样本数:
int nb_samples;
myfile.read((char*)&nb_samples, sizeof(nb_samples));
然后,这些样本的值...(在此存储为double
的vector
)
Then, the values for those samples... (here stored as a vector
of double
)
vector<double> vect;
vect.resize(nb_samples);
myfile.read((char*)&vect[0], nb_samples * sizeof(double));
等等...
但是,您再次打开的<c4>是由什么组成的?
But again, what the .wav
you opened is made of ?
一旦您完全掌握了内容,就可以采取另一种方式,从头开始编写自己的.wav
...
Once you completely master the content, you can go the other way and start writing your own .wav
from scratch...
Getting started - and here.
Bytes - "Autopsy" of a PCM Wav file.
这篇关于用C ++读写二进制文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!