动态创建的数组大小不正确

时间:2019-10-15 19:31:08

标签: c++ arrays binaryfiles

我正在努力手动解析二进制数据库文件。数据存储在固定宽度,固定长度的平面文件中,其中使用小尾数二进制值存储整数和日期。我要处理的类型有几种,从整数的单个字节到时间戳的7个字节。

我是C ++的新手,正在尝试重新创建在C#中所做的工作系统,但是有些事情使我不胜其烦。因此,我要做的第一件事就是从文件中将300个字节读取到wchar_t数组中。

int LineLength =300;
int counter = 0;
wint_t c;
wchar_t* wcs = new wchar_t[LineLength];
while ((c = fgetwc("BinaryFile.bin")) != WEOF) {
    wcs[counter] = c;
    counter++;
    if (counter > LineLength - 1) {
        break;
    }
}

这似乎很好。接下来,我需要创建动态数组大小,因为某些数据(例如int)将为1字节,某些数据将为字符串,并且长度更长。通常,我会通过循环JSON文件来设置所有ColumWidthStartingPosition等,但为简单起见,我只是将它们作为数组设置在这里:

string* ColumnName = new string[3]{ "Int1","Int2","String1" };
int*  StartingPosition =new int[3] { 1,10,11 };
int*  ColumnWidth =new int[3] { 4,1,25 };
for (int i = 0; 3 >= i; ++i)
{
    wchar_t* CurrentColumnBytes = new wchar_t[ColumnWidth[i]];
    cout << "\nBytes Requested: " << ColumnWidth[i]<< ", ArraySize: " << sizeof(CurrentColumnBytes) << "\n";

    int Counter = 0;
    for (int C = StartingPosition[i]; C <= ColumnWidth[i] + StartingPosition[i]; ++C)
    {
        CurrentColumnBytes[Counter] = wcs[C];
        Counter++;
    }

}

由于某种原因,CurrentColumnBytes总是具有4的大小。我将事情简化了一些:

int arraySize = 8;
char* locale = setlocale(LC_ALL, "UTF-8");
char* CurrentColumnBytes=new char[arraySize];
cout << "\nBytes Requested: " << arraySize << ", ArraySize: " << sizeof(CurrentColumnBytes) << "\n";

打印输出:Bytes Requested: 8, ArraySize: 4。将其更改为:

char* locale = setlocale(LC_ALL, "UTF-8");
char* CurrentColumnBytes[8];
cout << "ArraySize: " << sizeof(CurrentColumnBytes) << "\n";

此打印输出:ArraySize: 32这里似乎缺少一些基本内容。为什么不能创建具有所需宽度的数组?为什么在上一个示例中将它乘以4个字节?

是否有更好的方法来复制我使用C#所做的事情,像这样:

FileStream WorkingFile = new FileStream(fileName, FileMode.Open, FileAccess.Read);

while (WorkingFile.Position <= WorkingFile.Length)
{      
    byte[] ByteArray = new byte[300];
    WorkingFile.Read(ByteArray, 0, 300);
}

我也尝试使用ifstream,但是我认为创建正在处理的数组存在根本的误解。如果有人对更好的数据类型或方法提出建议,我将提供所有其他信息。

0 个答案:

没有答案