-
Notifications
You must be signed in to change notification settings - Fork 0
/
Reader.h
89 lines (72 loc) · 1.72 KB
/
Reader.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
#pragma once
#include <cstdio>
#include <cstring>
#include <iostream>
#include <stdexcept>
#include <vector>
// Source: http://corpus-texmex.irisa.fr/
class BaseVecsReader
{
int n;
protected:
FILE * fptr;
static const int DIM_SIZE = 4;
int d;
int curr{0};
public:
~BaseVecsReader() { if(fptr) close(); }
BaseVecsReader() = default;
BaseVecsReader(char *filename) { open(filename); }
void open(char * filename)
{
fptr = fopen(filename, "rb");
if (fptr == NULL)
{
printf("Error: %d (%s)\n", errno, strerror(errno));
exit(1);
}
fread(&d, sizeof(int), 1, fptr);
fseek(fptr, 0, SEEK_END);
int size = ftell(fptr);
n = size / ((1 + d) * DIM_SIZE);
fseek(fptr, 0, SEEK_SET);
}
void close() {
fclose(fptr);
curr = 0;
}
bool eof() { return feof(fptr) || curr >= n; }
inline int vec_id() { return curr; }
inline int num_vectors() { return n; }
// Skip the first 4 bytes that hold the dimension
inline void skip_dim() { fseek(fptr, DIM_SIZE, SEEK_CUR); }
inline int dimension() { return d; }
};
class FVecsReader: public BaseVecsReader
{
public:
float* readvec()
{
if(eof())
throw std::runtime_error("EOF reached");
float *arr = new float[d];
skip_dim();
fread(arr, sizeof(float), d, fptr);
curr++;
return arr;
}
};
class IVecsReader: public BaseVecsReader
{
public:
int *readvec()
{
if(eof())
throw std::runtime_error("EOF reached");
int *arr = new int[d];
skip_dim();
fread(arr, sizeof(int), d, fptr);
curr++;
return arr;
}
};