Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stddef.h>
- #include <stdlib.h>
- #include <string.h>
- /* readLines reads contents of a text file and returns a dynamically allocated string
- * containing the longest line of the file. Line is a sequence of characters terminated by the newline character '\n'.
- *
- * The length of the line is stored to the integer pointed to by
- * "longest". If the file does not contain any lines or if the file cannot be opened, then the value 0
- * is stored to the target of longest and NULL pointer is returned.
- *
- * If the file contains multiple lines with the longest length, then the first line encountered is returned.
- *
- * The returned value does not include the newline character. The caller of the function must free()
- * the returned value when it is no longer needed.
- */
- char *readLines(const char *file, size_t *longest){
- FILE* input = fopen(file, "r");
- if(input == NULL){
- *longest = 0;
- return NULL;
- }
- char buffer[1024];
- char *textFile = malloc(1);
- textFile[0] ='\0';
- size_t size = 0;
- while(fgets(buffer,1024,input)){
- size += strlen(buffer);
- textFile = realloc(textFile, size+1);
- strcat(textFile,buffer);
- }
- *longest = 0;
- char* newLine;
- const char* it = textFile;
- const char* lline = textFile;
- newLine = strchr(it,'\n');
- while(newLine != NULL){
- if((size_t)(newLine-it)>*longest){
- *longest = newLine-it;
- lline = it;
- }
- it = newLine+1;
- newLine = strchr(it,'\n');
- }
- //printf("longest is %zu\n", *longest);
- char *string = malloc((*longest)*sizeof(char));
- strncpy(string,lline,*longest);
- fclose(input);
- return string;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement