xouy 0 Newbie Poster

Hello,
I'm quite new to C programming, the code below tries to print the last 10 lines of a file,
My problem is in the last part of the function tail_file() : strcat(tail, character);
i'm reading the file character by character, but i want to return a string containing all of the 10 lines...
I can't figure out how to use strcat() to concatenate all the characters into the string tail and return it...

I hope I was clear, thank you so much for your help!

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#define NUMBER_OF_LINES 10
char * tail_file();

int main () {
	char * text;
	text=tail_file();
	printf("%s\n", text);
	free(text);
	return 0;
}

char * tail_file() {
        char character;
        char * tail=NULL; 
        tail = (char *) malloc(sizeof(char));
        void *abc;
        int num_lines=0,N_Lines_To_Print = NUMBER_OF_LINES;
        FILE *fd;

        // file open check
        if((fd = fopen("log.txt","r")) == NULL){
                printf("Unable to open the file\n");
        }

        // count the number of lines in the file.
        while(fread(&abc,1,1,fd))
        {
                character =(char *)abc;
                if(character == '\n')
                        num_lines++;
        }

        // get the value of the number of lines not to be printed       
        fseek(fd,0L,SEEK_SET);
        if(num_lines > N_Lines_To_Print)
                num_lines -= N_Lines_To_Print;
        else
                num_lines = 0;

        // start printing the file       
        while(fread(&abc,1,1,fd)){
                character = (char *)abc;
                if(!(num_lines)) {	
                	strcat(tail, &character);  // this line causes a segmentation fault
                        //printf("%c",character);
               	}
                else if(character == '\n') 
                	num_lines--;
        }

	return tail;
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.