Advertisement
triclops200

sts

Jul 22nd, 2012
262
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.69 KB | None | 0 0
  1. #include <cstring>
  2. #include <cstdio>
  3. #include <cstdlib>
  4. int strToLines(char**lines,char*input)
  5. {
  6.     int i = 0;
  7.     int maxsz = 1;
  8.     int len = 0;
  9.     char * de = (char*)malloc(maxsz*sizeof(char));
  10.     int maxszl = 1;
  11.     int lenl = 0;
  12.     lines = (char**)malloc(maxszl*sizeof(char*));
  13.     while(input[i])
  14.     {
  15.         char c = input[i++];
  16.         if(c == '\n')
  17.         {
  18.             de[len]=0;
  19.             lines[lenl++] = de;
  20.             if(lenl >= maxszl-1)
  21.             {
  22.                 lines = (char**)realloc(lines,sizeof(char*)*maxszl*2);
  23.                 maxszl*=2;
  24.             }
  25.             maxsz = 1;
  26.             len = 0;
  27.             de = (char*)malloc(sizeof(char)*maxsz);
  28.         }else
  29.         {
  30.             de[len++] = c;
  31.             if(len >= maxsz-1)
  32.             {
  33.                 de = (char*)realloc(de,sizeof(char)*maxsz*2);
  34.                 maxsz *=2;
  35.             }
  36.         }
  37.         i++;
  38.     }
  39.     de[len]=0;
  40.     lines[lenl++] = de;
  41.     return lenl;
  42. }
  43. char * readEntireFile(char * fname)
  44. {
  45.     int maxsz = 1;
  46.     int len = 0;
  47.     char * str = (char*)calloc(sizeof(char),maxsz);
  48.     char b[33];
  49.     b[32]=0;
  50.     int camt;
  51.     FILE * f = fopen(fname,"r");
  52.     while(camt=fread(b,1,32,f)){
  53.         len += camt;
  54.         while(len >= maxsz-1){
  55.             str=(char*)realloc(str,sizeof(char)*maxsz*2);
  56.             maxsz *=2;
  57.         }
  58.         strcat(str,b);
  59.     }
  60.     str[len]=0;
  61.     fclose(f);
  62.     return str;
  63. }
  64. int main()
  65. {
  66.     char * str = readEntireFile("test.cpp");
  67.     char ** lines;
  68.     int l = strToLines(lines,str);
  69.     free(str);
  70.     for(int i = 0; i < l; i++)
  71.     {
  72.         printf("%s\n",lines[i]);
  73.         free(lines[i]);
  74.     }
  75. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement