从文件中读取某些整数,就像从VB6中一样

C++ Read certain integers from file as from VB6

本文关键字:VB6 一样 读取 文件 整数      更新时间:2023-10-16

我想使用c++从文件中提取一些整数,但我不确定我是否做得正确。

我的VB6代码如下:

Redim iInts(240) As Integer
Open "m:devvoice.raw" For Binary As #iFileNr
Get #iReadFile, 600, iInts() 'Read from position 600 and read 240 bytes

我向c++的转换如下:

vector<int>iInts
iInts.resize(240)
FILE* m_infile;
string filename="m://dev//voice.raw";
if (GetFileAttributes(filename.c_str())==INVALID_FILE_ATTRIBUTES)
{
  printf("wav file not found");
  DebugBreak();
} 
else 
{
  m_infile = fopen(filename.c_str(),"rb");
}

但现在我不知道如何从那里继续,我也不知道"rb"是否正确。

我不知道VB如何读取文件,但如果您需要从文件中读取整数,请尝试:

m_infile = fopen(myFile, "rb")
fseek(m_infile, 600 * sizeof(int), SEEK_SET);
// Read the ints, perhaps using fread(...)
fclose(myFile);

或者您可以使用c++的方式使用ifstream

带有流的完整示例(注意,您应该添加错误检查):

#include <ifstream>
void appendInts(const std::string& filename, 
                unsigned int byteOffset, 
                unsigned int intCount,
                const vector<int>& output)
{
    std::ifstream ifs(filename, std::ios::base::in | std::ios::base::binary);
    ifs.seekg(byteOffset);
    for (unsigned int i = 0; i < intCount; ++i)
    {
        int i;
        ifs >> i;
        output.push_back(i);
    }
}
...
std::vector<int> loadedInts;
appendInts("myfile", 600, 60, loadedInts);

使用整型数组代替矢量,并传递poth文件描述符和数组指针给函数read()如下

...
int my_integers[240];
read(m_infile, my_integers, 240, 600);
..

有关read()的更多信息,请参阅http://pubs.opengroup.org/onlinepubs/009695399/functions/read.html