-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparser.cpp
More file actions
301 lines (244 loc) · 8.36 KB
/
parser.cpp
File metadata and controls
301 lines (244 loc) · 8.36 KB
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
/*
Parser
Alunos: Davi Ricardo
Emidio Jose
Enzo Henrique
*/
#include <iostream> // cout, endl
#include "parser.hpp"
int colisoes=0;
//Passa o conteúdo de b para a via ponteiro.
void copyStringToStr(char* a, string b, int tam) {
strncpy(a, b.c_str(), tam);
a[tam-1] = 0;
}
//Imprime os dados do artigo em questão.
void imprimirArtigo(Artigo art) {
cout<< "\n*ID: " << art.id
<< "\n*Titulo: " << art.titulo
<< "\n*Ano: " << art.ano
<< "\n*Autor: " << art.autor
<< "\n*Citações:" << art.citacoes
<< "\n*Atualização: " << art.atualizacao
<< "\n*Snippet: " << art.snippet
<< endl << endl;
}
//Faz uma copia do artigo.
void copiaArtigo(Artigo *destino, Artigo *fonte){
destino->id = fonte->id;
strcpy(destino->titulo,fonte->titulo);
destino->ano = fonte->ano;
strcpy(destino->autor,fonte->autor);
destino->citacoes = fonte->citacoes;
strcpy(destino->atualizacao,fonte->atualizacao);
strcpy(destino->snippet,fonte->snippet);
}
void pause() {
std::cout << "Press enter to continue ...";
cin.get();
}
//Pega os campos do argumento passado. verifica se possui aspas, se há espaçamento ou puladas de linha.
string getCampo(ifstream *arq){
string coluna;
int numAspas = 0;
char anterior = 0, atual;
bool acabou = false;
while(!acabou) {
if(!arq->get(atual)) {
return "";
}
switch(atual) {
case '"':
numAspas++;
break;
case '\r':
//Lê e ignora o próximo caracter, no caso '\n'
arq->get();
case ';':
if(coluna == "NULL"){
return coluna;
}
else if (
//Se não tiver aspas delimitando o campo ou se for um caso de aspas aninhadas ""
numAspas == 0 ||
(anterior=='"' && (numAspas&1)==0)//Verifica se numAspas é par
)
{
acabou = true;
}
break;
default:;
}
coluna += anterior = atual;
}
return coluna.substr (1,coluna.length()-3);
}
//Retorna um bucket do hashfile através da busca por ID.
Bloco getBucketHashFileByID(fstream *arq, int id) {
Bloco buffer={0};
int i,j;
//Encontrando a posição do bucket no hashfile
int enderecoBucket = hashSimples(id);
arq->seekg (enderecoBucket*sizeof(Bloco),ios::beg);
//Leitura de Bloco
arq->read((char*)&buffer,sizeof(Bloco));
return buffer;
}
//Retorna um ponteiro do bucket do hashfile através da busca por posicão no hashfile.
Bloco * getBucketHashFileByPosition(fstream *arq, int position) {
Bloco *buffer= NULL;
int i,j;
buffer = (Bloco *)malloc(sizeof(Bloco));
//Encontrando a posição do bucket no hashfile
arq->seekg (position*sizeof(Bloco),ios::beg);
//Leitura de Bloco
arq->read((char*)buffer,sizeof(Bloco));
return buffer;
}
//Pega o artigo no hashfile através da posição em que se encontra e verifica se o id do artigo e o id de entrada são iguais.
Artigo* getArtigoByPositionID(fstream *arq, int position, int id){
Bloco *bucket;
Artigo *article, *result=NULL;
int maior, menor, posicaoPonteiro;
result = (Artigo *) malloc(sizeof(Artigo));
bucket = getBucketHashFileByPosition(arq, position);
article = (Artigo*)&bucket->corpo;
menor=0;
maior=bucket->numRegistros-1;
while(menor <= maior){
posicaoPonteiro = (menor + maior) / 2;
if(id == article[posicaoPonteiro].id){
copiaArtigo(result, &article[posicaoPonteiro]);
break;
}else if(id < article[posicaoPonteiro].id){
maior = posicaoPonteiro - 1;
}else{
menor = posicaoPonteiro + 1;
}
}
free(bucket);
return result;
}
//Pega o artigo no arquivo hash através da posição em que se encontra e verifica se o título do artigo e o título de entrada são iguais.
Artigo* getArtigoByPositionTitle(fstream *arq, int position, char title[300]){
Bloco *bucket;
Artigo *article, *result=NULL;
result = (Artigo *) malloc(sizeof(Artigo));
bucket = getBucketHashFileByPosition(arq, position);
article = (Artigo*)&bucket->corpo;
for(int i=0; i < bucket->numRegistros; i++){
if(strcmp(title, article[i].titulo) == 0){
copiaArtigo(result, &article[i]);
break;
}
}
free(bucket);
return result;
}
//Retorna o artigo do arquivo
Artigo getArtigo(ifstream *arq) {
string aux;
Artigo artigo = {0};
for(int estado = 1; estado <= 7; estado++) {
aux = getCampo(arq);
if(aux=="NULL") {
break;
}
switch(estado) {
case (1):
artigo.id=atoi(aux.c_str());
break;
case (2):
copyStringToStr(artigo.titulo,aux,300);
break;
case (3):
artigo.ano =atoi(aux.c_str());
break;
case (4):
copyStringToStr(artigo.autor,aux,100);
break;
case (5):
artigo.citacoes = atoi(aux.c_str());
break;
case (6):
copyStringToStr(artigo.atualizacao,aux,20);
break;
case (7):
copyStringToStr(artigo.snippet,aux,100);
break;
}
}
return artigo;
}
//Retorna o bucket que possui o id de entrada.
int hashSimples(int id) {
return id%NUM_BUCKETS;
}
//Insere no arquivo hash o ponteiro que identifica tal artigo
int inserirNoHashFile(fstream *arq, Artigo artigo) {
int i,j;
Bloco buffer= getBucketHashFileByID(arq,artigo.id);
//Interpretar o corpo do bloco como um vetor de artigos, o tamanho do vetor é dado por buffer.numRegistros (cabeçalho)
Artigo *vet;
vet=(Artigo*)&buffer.corpo;
//Verificando se há espaço no bloco
if(buffer.numRegistros < FATOR_BLOCO) {
for(i=0; i<buffer.numRegistros; i++) {
//imprimirArtigo(artigo);
if(artigo.id < vet[i].id) {
//Deslocar todos os artigos
for(j=buffer.numRegistros; j>i; j--) {
//Cada artigo recebe o que estava no anterior
memcpy(&vet[j],(char*)&vet[i-1], sizeof(Artigo));
}
break;
}
/*
else if (artigo.id == vet[i].id) {
//Artigo já está no hash
return;
}
*/
}
//Insere o artigo em sua devida posição
memcpy(&vet[i],(char*)&artigo, sizeof(Artigo));
//Atualizar o número de registros
buffer.numRegistros=buffer.numRegistros+1;
//Volta o cursor para o início do bloco atual, para sobrescrevê-lo
arq->seekp( - sizeof(Bloco) , ios::cur);
//Escreve o bloco no arquivo
arq->write((char*)&buffer,sizeof(Bloco));
return 1;
}
else {
//Numero de Buckets insuficientes
colisoes++;
return -1;
//cout<< "Houve colisão ID: "<<contRegistro<<endl;
}
}
// Busca no arquivo de dados por um registro com o ID informado, se existir, e retornar os campos do registro, a quantidade de blocos lidos para encontrá-lo e a quantidade total de bloco do arquivo de dados;
Artigo findrec(fstream *arq,int id, bool imprimir) {
int contBlocosLidos =0;
Bloco buffer= getBucketHashFileByID(arq,id);
contBlocosLidos++;
//Interpretar o corpo do bloco como um vetor de artigos, o tamanho do vetor é dado por buffer.numRegistros (cabeçalho)
Artigo *vet;
vet=(Artigo*)&buffer.corpo;
//Verificar se o registro já foi inserido
for(int i=0; i<buffer.numRegistros; i++) {
//imprimirArtigo(vet[i]);
if(id == vet[i].id) {
if(imprimir) {
imprimirArtigo(vet[i]);
cout<< "------------------------------------------------\nBlocos lidos: "<<contBlocosLidos<<" Total de Blocos: "<<NUM_BUCKETS<<endl;
}
return vet[i];
}
}
cout << "Não encontrado.\n";
}
//Retorna as colisões no arquivo hash.
int getColisoes() {
return colisoes;
}