Advertisement
Guest User

Untitled

a guest
Sep 20th, 2017
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.60 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.         textFile = realloc(textFile, size+1);
  31.         strcat(textFile,buffer);
  32.     }
  33.     *longest = 0;
  34.     char* newLine;
  35.     const char* it = textFile;
  36.     const char* lline = textFile;
  37.     newLine = strchr(it,'\n');
  38.     while(newLine != NULL){
  39.         if((size_t)(newLine-it)>*longest){
  40.             *longest = newLine-it;
  41.             lline = it;
  42.         }
  43.         it = newLine+1;
  44.         newLine = strchr(it,'\n');
  45.     }
  46.     //printf("longest is %zu\n", *longest);
  47.     char *string = malloc((*longest)*sizeof(char));
  48.     strncpy(string,lline,*longest);
  49.     fclose(input);
  50.     return string;
  51.    
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement