2013-01-06 61 views
-1

我想从使用C++的文件中提取一些整数,但我不确定自己是否正确地做了。C++从VB6读取文件中的某些整数

我在VB6的代码如下:

Redim iInts(240) As Integer 
Open "m:\dev\voice.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”是否正确。

+2

我建议使用C++ I/O str Eams而不是低级API,操作符>>有几个重载,这使得提取基本数据类型的值非常容易 –

+0

代码中有很多特定于Windows的API。添加标签。 –

+0

对VB语句的评论似乎是一种触动。它读取的是240 *字节*还是240 *整数*(或者可能是240个8位整数?)要知道如何写出所写的内容,您首先必须知道它是如何写入的。 – WhozCraig

回答

1

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

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

或者你可以使用使用ifstream的 C++的方式。

与流完整的示例(注意,应添加错误检查):

#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); 
+0

您能否填写您发表评论的地方?我对C++没有经验,这不是世界上最简单的任务。 – tmighty

+0

检查fread文档,例如http://www.cplusplus.com/reference/cstdio/fread/。 或者再次使用C++方式处理流http://www.cplusplus.com/reference/fstream/ifstream/。 –

+0

我真的很好奇,并且会在发布后查找我自己,但是在* binary *模式下打开的'ifstream'上,格式化提取操作符>> operator()的行为究竟是什么? – WhozCraig