Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- typedef struct _t_line {
- struct _t_line *next;
- size_t offset;
- size_t length;
- } t_line;
- static t_line *list = NULL;
- void read_to_list(char *fname, t_line **list)
- {
- if (!list)
- return;
- FILE *f = fopen(fname, "rb");
- if (!f)
- return;
- t_line *cur = *list;
- size_t offset = 0;
- while (!feof(f))
- {
- while (fgetc(f) != '\n')
- if (feof(f))
- break;
- t_line *new_item = malloc(sizeof(t_line));
- if (!new_item)
- return;
- new_item->next = NULL;
- new_item->offset = offset;
- new_item->length = ftell(f) - offset;
- //printf("o: %d l: %d\n", new_item->offset, new_item->length);
- offset = ftell(f);
- if (!cur) {
- *list = new_item;
- cur = new_item;
- } else {
- cur->next = new_item;
- cur = new_item;
- }
- }
- fclose(f);
- }
- void print_list(t_line *list)
- {
- if (!list)
- return;
- do {
- printf("o: %d l: %d\n", list->offset, list->length);
- list = list->next;
- } while (list);
- return;
- }
- char *get_line_at(char *fname, t_line *list, size_t idx)
- {
- if (!list)
- return NULL;
- for (size_t i = 0; i < idx; i++) {
- list = list->next;
- if (!list)
- return NULL;
- }
- //printf("o: %d l: %d\n", list->offset, list->length);
- FILE *f = fopen(fname, "rb");
- if (!f)
- return NULL;
- fseek(f, list->offset, SEEK_SET);
- char *line = calloc(list->length + 1, 1);
- if (!line) {
- fclose(f);
- return NULL;
- }
- fread(line, sizeof(char), list->length, f);
- fclose(f);
- return line;
- }
- int main (int argc, char **argv)
- {
- read_to_list(__FILE__, &list);
- print_list(list);
- puts(get_line_at(__FILE__, list, 3));
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement