需要帮助将C ++翻译成C#

时间:2010-07-20 03:08:35

标签: c# c translation

我不太熟悉C ++,特别是IO部分。任何人都可以帮我把以下C ++代码翻译成C#?

unsigned *PostingOffset, *PostingLength, NumTerms;

void LoadSubIndex(char *subindex) {
  FILE *in = fopen(subindex, "rb");
  if (in == 0) {
    printf("Error opening sub-index file '%s'!\n", subindex);
    exit(EXIT_FAILURE);
  }
  int len=0;
  // Array of terms
  char **Term;
  char *TermList;
  fread(&NumTerms, sizeof(unsigned), 1, in);
  PostingOffset = (unsigned*)malloc(sizeof(unsigned) * NumTerms);
  PostingLength = (unsigned*)malloc(sizeof(unsigned) * NumTerms);
  Term = (char**)malloc(sizeof(char*) * NumTerms);
  Term = (char**)malloc(sizeof(char*) * NumTerms);
  // Offset of each posting
  fread(PostingOffset, sizeof(unsigned), NumTerms, in);
  // Length of each posting in bytes
  fread(PostingLength, sizeof(unsigned), NumTerms, in);
  // Number of bytes in the posting terms array
  fread(&len, sizeof(unsigned), 1, in); 
  TermList = (char*)malloc(sizeof(char) * len);
  fread(TermList, sizeof(unsigned)*len, 1, in);

  unsigned k=1;
  Term[0] = &TermList[0];
  for (int i=1; i<len; i++) {
    if (TermList[i-1] == '\0') {
      Term[k] = &TermList[i];
      k++;
    }
  }
  fclose(in);
}

提前致谢。

1 个答案:

答案 0 :(得分:6)

我会给你一个头脑。

using(var reader = new BinaryReader(new FileStream(subindex, FileMode.Open)) {
    int numTerms = reader.ReadUInt32();
    postingOffset = new UInt32[numTerms];
    postingLength = new UInt32[numTerms];
    var term = new byte[numTerms];
    for(int i=0;i<numTerms;i++)
        postingOffset[i] = reader.ReadUInt32();
    for(int i=0;i<numTerms;i++)
        postingLength[i] = reader.ReadUInt32();
    var len = reader.ReadInt32();
    var termList = new ... // byte[] or uint32[] ??
    //etc
}

此处无需关闭文件句柄 - 当使用{}块失去范围时,它将关闭。

我没有完成它,因为你的代码中存在一些缺陷。使用TermList,您读取的数据是您分配的数据的4倍。你不应该两次分配Term - 这将导致内存泄漏。

要将Term转回字符串,请使用Encoding.ASCII.GetString(term).TrimEnd('\0');