Advertisement
fippo

Untitled

Apr 10th, 2013
2,062
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.00 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <memory.h>
  4.  
  5. int main(void)
  6. {
  7.     FILE* f;
  8.     char* buffer = 0;
  9.     char** lines = 0;
  10.     long length;
  11.     long prevPos;
  12.     long currentLine;
  13.     long i;
  14.  
  15.     f = fopen("file.txt", "r");
  16.  
  17.     if (!f) {
  18.         printf("failed to open file");
  19.         exit(42);
  20.     }
  21.  
  22.     // Определяем размер файла
  23.     fseek(f, 0, SEEK_END);
  24.     length = ftell(f);
  25.     fseek(f, 0, SEEK_SET);
  26.  
  27.     // Выделяем массив данного размера
  28.     buffer = malloc(length);
  29.     if (buffer) {
  30.         // Читаем весь файл в массив
  31.         fread(buffer, 1, length, f);
  32.     }
  33.     fclose(f);
  34.  
  35.     if (!buffer) {
  36.         printf("read nothing");
  37.         exit(42);
  38.     }
  39.  
  40.     long linesCount = 1;
  41.     // Считаем количество строчек,
  42.     for (i = 0; i < length; i++) {
  43.         if (buffer[i] == '\n') {
  44.             linesCount++;
  45.         }
  46.     }
  47.  
  48.     printf("Lines count: %d\n", (int)linesCount);
  49.  
  50.     // Выделяем память под указатели на строчки
  51.     lines = malloc(linesCount * sizeof(char*));
  52.     currentLine = 0;
  53.     prevPos = 0;
  54.     for (i = 0; i < length; i++) {
  55.         if (buffer[i] == '\n' || i == length - 1) {
  56.             lines[currentLine] = malloc(i - prevPos + 1);
  57.             memcpy(lines[currentLine], &buffer[prevPos], i - prevPos);
  58.             lines[currentLine][i - prevPos] = 0; // Последний символ в строке 0
  59.             prevPos = i + 1; // +1 для windows (там где \r\n)
  60.             currentLine++;
  61.         }
  62.     }
  63.     free(buffer);
  64.  
  65.     // Имеем массив lines в котором linesCount строк
  66.     for (i = 0; i < linesCount; i++) {
  67.         printf("%s\n", lines[i]);
  68.     }
  69.  
  70.  
  71.     // Не забыть освободить нааллоцированное:
  72.     for (i = 0; i < linesCount; i++) {
  73.         free(lines[linesCount]);
  74.     }
  75.     free(lines);
  76.  
  77.     return 0;
  78. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement