Advertisement
Guest User

Untitled

a guest
Apr 21st, 2014
108
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.63 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. typedef struct _t_line {
  5.     struct _t_line *next;
  6.     size_t offset;
  7.     size_t length;
  8. } t_line;
  9.  
  10. static t_line *list = NULL;
  11.  
  12. void read_to_list(char *fname, t_line **list)
  13. {
  14.     if (!list)
  15.         return;
  16.  
  17.     FILE *f = fopen(fname, "rb");
  18.     if (!f)
  19.         return;
  20.  
  21.     t_line *cur = *list;
  22.     size_t offset = 0;
  23.     while (!feof(f))
  24.     {
  25.         while (fgetc(f) != '\n')
  26.             if (feof(f))
  27.                 break;
  28.         t_line *new_item = malloc(sizeof(t_line));
  29.         if (!new_item)
  30.             return;
  31.         new_item->next = NULL;
  32.         new_item->offset = offset;
  33.         new_item->length = ftell(f) - offset;
  34.         //printf("o: %d l: %d\n", new_item->offset, new_item->length);
  35.  
  36.         offset = ftell(f);
  37.  
  38.         if (!cur) {
  39.             *list = new_item;
  40.             cur = new_item;
  41.         }   else {
  42.             cur->next = new_item;
  43.             cur = new_item;
  44.         }
  45.     }
  46.  
  47.     fclose(f);
  48. }
  49.  
  50. void print_list(t_line *list)
  51. {
  52.     if (!list)
  53.         return;
  54.     do {
  55.         printf("o: %d l: %d\n", list->offset, list->length);
  56.         list = list->next;
  57.     } while (list);
  58.     return;
  59. }
  60.  
  61. char *get_line_at(char *fname, t_line *list, size_t idx)
  62. {
  63.     if (!list)
  64.         return NULL;
  65.  
  66.     for (size_t i = 0; i < idx; i++) {
  67.         list = list->next;
  68.         if (!list)
  69.             return NULL;
  70.     }
  71.     //printf("o: %d l: %d\n", list->offset, list->length);
  72.  
  73.     FILE *f = fopen(fname, "rb");
  74.     if (!f)
  75.         return NULL;
  76.     fseek(f, list->offset, SEEK_SET);
  77.     char *line = calloc(list->length + 1, 1);
  78.     if (!line) {
  79.         fclose(f);
  80.         return NULL;
  81.     }
  82.     fread(line, sizeof(char), list->length, f);
  83.     fclose(f);
  84.     return line;
  85. }
  86.  
  87. int main (int argc, char **argv)
  88. {
  89.     read_to_list(__FILE__, &list);
  90.     print_list(list);
  91.     puts(get_line_at(__FILE__, list, 3));
  92.     return 0;
  93. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement