[英]Need help in translating C++ to C#
I don't know C++ very well especially the IO part. 我不太了解C ++,尤其是IO部分。 Can anyone please help me to translate the following C++ code into C#? 谁能帮助我将以下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);
}
Thanks in advance. 提前致谢。
I'll give you a headstart. 我给你一个开端。
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
}
There's no need to close the file handle here - it will close when the using { } block loses scope. 此处无需关闭文件句柄-当using {}块失去作用域时,它将关闭。
I didn't finish it because there are some flaws in your code. 我没有完成它,因为您的代码中存在一些缺陷。 With TermList
you are reading in 4 times as much data as you've allocated. 使用TermList
您读取的数据量是分配的4倍。 You shouldn't be allocating Term
twice either - that will result in leaking memory. 您也不应该两次分配Term
这将导致内存泄漏。
To turn Term back into a string, use Encoding.ASCII.GetString(term).TrimEnd('\\0')
; 要将Term转换回字符串,请使用Encoding.ASCII.GetString(term).TrimEnd('\\0')
;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.