2 #include <stdlib.h> // malloc(), free()
4 File
*filebuffers
= NULL
;
5 uint64_t numbuffers
= 0;
8 // we don't read 1 char at a time, because then we would have to either reallocate each line again for each character read or allocate a huge buffer
9 int readfile(char *fn
) {
10 filebuffers
= malloc(sizeof(File
) * 5);
12 uint64_t numlines
= 0, linechars
= 0, filechars
, i
, index
; // Unfortunately, this does not work on files of more than 18446744073709551616 bytes
14 uint32_t *linelengths
;
20 tmp
.fp
= fopen(tmp
.fn
, "r");
29 // Credit to http://stackoverflow.com/a/3464656
30 fseek(tmp
.fp
, 0, SEEK_END
);
31 filechars
= ftell(tmp
.fp
);
34 buf
= malloc(sizeof(char) * filechars
);
36 fread(buf
, sizeof(char), filechars
, tmp
.fp
);
39 for (i
= 0; i
< filechars
; ch
= buf
[i
++]) {
44 tmp
.text
= malloc(sizeof(char*) * numlines
);
45 linelengths
= malloc(sizeof(uint64_t) * numlines
);
47 tmp
.numlines
= numlines
;
49 // count the number of chars in each line
50 for (i
= 0; i
< filechars
; ch
= buf
[i
++]) {
52 linelengths
[line
] = linelength
;
60 for (i
= 0; i
< numlines
+1; i
++) {
61 tmp
.text
[i
] = malloc(sizeof(char) * (linelengths
[1] + 2));
66 // actually read the lines out
67 for (i
= 0; i
< filechars
; ch
= buf
[i
++]) {
69 (tmp
.text
[line
])[index
] = '\0';
73 (tmp
.text
[line
])[index
] = ch
;
80 void closebuffer(int index
) {
81 if ((index
>= numbuffers
) || (numbuffers
== 0)) {
85 if (!(filebuffers
[index
].isclosed
)) {
86 fclose(filebuffers
[index
].fp
);
89 File
*files
= malloc(sizeof(File
)*(numbuffers
-1));
91 if (index
!= 0) {for (int i
=0; i
< index
; i
++) {
92 files
[i
] = filebuffers
[i
];
95 if (index
!= numbuffers
-1) { for (int i
=index
+1; i
< numbuffers
-1; i
++) {
96 files
[i
-1] = filebuffers
[i
];
105 void closeallbuffers() {