Guest User

Untitled

a guest
Dec 10th, 2015
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.11 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4.  
  5. unsigned get_iterations(FILE *fp, const char delimiter)
  6. {
  7.     long pos = ftell(fp);
  8.     unsigned cases = 0;
  9.     char c;
  10.     while ((c = fgetc(fp)) && !feof(fp))
  11.     {
  12.         if (c == delimiter)
  13.             cases++;
  14.     }
  15.     fseek(fp, pos, SEEK_SET);
  16.     return cases;
  17. }
  18.  
  19. unsigned get_linelength(FILE *fp, const char delimiter)
  20. {
  21.     long pos = ftell(fp);
  22.     unsigned len = 2; /* this refuses to work unless it's 2+ */
  23.     while (fgetc(fp) != delimiter)
  24.     {
  25.         len++;
  26.     }
  27.     fseek(fp, pos, SEEK_SET);
  28.     return len;
  29. }
  30.  
  31. int main(int argc, char **argv)
  32. {
  33.     if (argc != 2)
  34.     {
  35.         printf("usage: %s %s\n", argv[0], "filename");
  36.         return 0;
  37.     }
  38.     FILE *file = fopen(argv[1], "r");
  39.     if (!file)
  40.     {
  41.         perror("Could not open file.\n");
  42.         return 1;
  43.     }
  44.     char arr[1000][1000] = { {0} };
  45.     unsigned cases = get_iterations(file, '\n');
  46.     unsigned i = 0;
  47.     while (i++ < cases)
  48.     {
  49.         unsigned len = get_linelength(file, '\n');
  50.         char *str = (char *) malloc(sizeof(char) * len);
  51.         fgets(str, len, file);
  52.         printf("test: len %u, str: %s\n", len, str);
  53.         free(str);
  54.     }
  55.     fclose(file);
  56.     return 0;
  57. }
Advertisement
Add Comment
Please, Sign In to add comment