C / C ++读取具有多个字符串和字符的二进制文件

时间:2012-10-09 03:59:57

标签: c++ c pointers malloc fread

我的目标是从一百多个“序列”(非技术术语)中读取二进制文件,每个序列包含一个char1(要跟随的字符串的长度),string1,char2,string2。这里的关键似乎是动态内存分配,指针和循环。我就这样做了:

char *ColumnNameLength = (char *) malloc(Repetitions * sizeof(char));
char *DataTypeLength = (char *) malloc(Repetitions * sizeof(char)); 
char **ColumnName = (char **) malloc(Repetitions * sizeof(char));
char **DataType = (char **) malloc(Repetitions * sizeof(char));

for (int ctr = 0; ctr <= Repetitions ; ColumnNameLength[ctr] = DataTypeLength[ctr] = NULL, ctr++)
    ;
for (int ctr = 0; ctr <= Repetitions ; *(ColumnName+ctr) = DataType[ctr] = NULL, ctr++)
    ;

for (int ctr = 0; ctr <= FieldCount; ctr++)
{
    fread((ColumnNameLength + ctr), sizeof(char), 1, pInfile);

    *(ColumnName + ctr) = (char *) malloc(ColumnNameLength[ctr] * sizeof(char));
    fread(ColumnName[ctr], sizeof(char), ColumnNameLength[ctr], pInfile);
    //I should add '\0' at the end of each read string, but no idea how

    fread((DataTypeLength + ctr), sizeof(char), 1, pInfile);

    *(DataType + ctr) = (char *) malloc(DataTypeLength[ctr] * sizeof(char));
    fread(&DataType[ctr], sizeof(char), DataTypeLength[ctr], pInfile);
    //I should add '\0' at the end of each read string, but no idea how

}

不幸的是,这不起作用,我甚至不知道是否要开始调试。任何建议将不胜感激。

3 个答案:

答案 0 :(得分:1)

  • 确保使用sizeof(char*)而非sizeof(char)
  • 分配字符串数组
  • 也许使用unsigned char来表示长度,以避免信号混淆。
  • 为尾随'\0'分配一个字符。
  • 使用ColumnName[ctr][ColumnNameLength[ctr]] = '\0'添加尾随空字节。
  • malloc returnins NULL
  • 的情况下添加一些错误检查
  • 添加错误检查,以防fread返回长度以外的其他内容。
  • 在未来的问题中,更具体地说明实际失败的原因。

答案 1 :(得分:1)

我在您的代码中看到的第一个错误是使用&lt; =而不是&lt; ,你有ColumnNameLength个字符可以覆盖,因此从索引0到索引ColumnNameLength -1

对我来说,使用指针指针而不是使用char数组来保存字符串是很奇怪的。

答案 2 :(得分:0)

char *ColumnNameLength = (char *) malloc(Repetitions * sizeof(char));
char *DataTypeLength = (char *) malloc(Repetitions * sizeof(char)); 
char **ColumnName = (char **) malloc(Repetitions * sizeof(char*));
char **DataType = (char **) malloc(Repetitions * sizeof(char*));

for (int ctr = 0; ctr <= Repetitions ; ColumnNameLength[ctr] = DataTypeLength[ctr] = NULL, ctr++)
    ;
for (int ctr = 0; ctr <= Repetitions ; ColumnName[ctr] = DataType[ctr] = NULL, ctr++)
    ;

for (int ctr = 0; ctr <= FieldCount; ctr++)
{
    fread((ColumnNameLength + ctr), sizeof(char), 1, pInfile);

    ColumnName[ctr] = (char *) malloc((ColumnNameLength[ctr]+1) * sizeof(char));
    fread(ColumnName[ctr], sizeof(char), ColumnNameLength[ctr], pInfile);
    //I should add '\0' at the end of each read string, but no idea how
    ColumnName[ctr][ColumnNameLength[ctr]] = '\0';

    fread((DataTypeLength + ctr), sizeof(char), 1, pInfile);

    DataType[ctr] = (char *) malloc((DataTypeLength[ctr]+1) * sizeof(char));
    fread(DataType[ctr], sizeof(char), DataTypeLength[ctr], pInfile);
    //I should add '\0' at the end of each read string, but no idea how
    DataType[ctr][DataTypeLength[ctr]] = '\0';

}