-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdocument.c
77 lines (66 loc) · 2.09 KB
/
document.c
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
/* -*- mode: c; c-basic-offset: 4; indent-tabs-mode: nil; -*-
*
* Copyright (c) 2008 Jeremy English <[email protected]>
*
* Permission to use, copy, modify, distribute, and sell this software and its
* documentation for any purpose is hereby granted without fee, provided that
* the above copyright notice appear in all copies and that both that
* copyright notice and this permission notice appear in supporting
* documentation. No representations are made about the suitability of this
* software for any purpose. It is provided "as is" without express or
* implied warranty.
*
* Created: 01-November-2008
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "document.h"
#include "eprintf.h"
#include "fileutils.h"
DocumentManager *open_document_manager(char *output_file,
BinaryFileMode mode){
DocumentManager *dm;
dm = emalloc(sizeof(*dm));
dm->filename = estrdup(output_file);
dm->doc_id = 0;
dm->fp = open_binary_file(output_file, mode);
return dm;
}
void write_document(DocumentManager *dm, char *filename){
Document doc;
int i,j;
if (strlen(filename) > MAX_DOCUMENT_NAME){
fprintf(stderr,
"%s: Filename is to long. Cannot write to the document file.\n",
progname());
}
j = 0;
for (i = 0; i < MAX_DOCUMENT_NAME; i++){
if (filename[j] != '\0'){
doc.data[i] = filename[j++];
}
else{
doc.data[i] = '\0';
}
}
fwrite(&doc, sizeof(doc), 1, dm->fp);
dm->doc_id++;
}
void close_document_manager(DocumentManager *dm){
free(dm->filename);
dm->filename = NULL;
fclose(dm->fp);
}
void get_document(DocumentManager *dm, Document *doc, int docid){
int sz = sizeof(Document);
int offset = docid * sz;
int n;
fseek(dm->fp, offset, SEEK_SET);
if ((n = fread(doc,sz,1,dm->fp)) != 1){
int errcode = ferror(dm->fp);
fprintf(stderr,"%s Could not read record %d. Error code %d\n",
progname(), docid, errcode);
exit(1);
}
}