Advertisement
Guest User

Untitled

a guest
Sep 20th, 2017
59
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.65 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stddef.h>
  3. #include <stdlib.h>
  4. #include <string.h>
  5.  
  6. /* readLines reads contents of a text file and returns a dynamically allocated string
  7.  * containing the longest line of the file. Line is a sequence of characters terminated by the newline character '\n'.
  8.  *
  9.  * The length of the line is stored to the integer pointed to by
  10.  * "longest". If the file does not contain any lines or if the file cannot be opened, then the value 0
  11.  * is stored to the target of longest  and NULL pointer is returned.
  12.  *
  13.  * If the file contains multiple lines with the longest length, then the first line encountered is returned.
  14.  *
  15.  * The returned value does not include the newline character. The caller of the function must free()
  16.  * the returned value when it is no longer needed.
  17.  */
  18. char *readLines(const char *file, size_t *longest){
  19.     FILE* input = fopen(file, "r");
  20.     if(input == NULL){
  21.         *longest = 0;
  22.         return NULL;
  23.     }
  24.     char buffer[1024];
  25.     char *textFile = malloc(1);
  26.     textFile[0] ='\0';
  27.     size_t size = 0;
  28.     while(fgets(buffer,1024,input)){
  29.         size += strlen(buffer);
  30.         printf("textfile size is %zu\n", size);
  31.         textFile = realloc(textFile, size+1);
  32.         strcat(textFile,buffer);
  33.     }
  34.     *longest = 0;
  35.     if(size == 0){
  36.         free(textFile);
  37.         return NULL;
  38.     }
  39.  
  40.     char* newLine;
  41.     const char* it = textFile;
  42.     const char* lline = textFile;
  43.     newLine = strchr(it,'\n');
  44.     while(newLine != NULL){
  45.         if((size_t)(newLine-it)>*longest){
  46.             *longest = newLine-it;
  47.             lline = it;
  48.         }
  49.         it = newLine+1;
  50.         newLine = strchr(it,'\n');
  51.     }
  52.     char *string = malloc(*longest);
  53.     strncpy(string,lline,*longest);
  54.     fclose(input);
  55.     return string;
  56.    
  57. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement