Click here to Skip to main content
15,918,275 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I try to implement tail -n function, but it is not efficiently, can you help me to implement in another way ? This is my code

function must display the last n lines of the file
Thanks!

What I have tried:

C#
void tail_n(){
	m=atoi(params[2]);
	file_name1=fopen(params[3],"r");
	if ( file_name1 != NULL )
   	{
		while (fgets(line, 199, file_name1) != NULL)
		{
			count++;// numarul de linii din fisier
			
		}

		count1=count-m;// nr de linii de unde incep afisarea
		
	file_name1=fopen(params[3],"r");
	if(file_name1 !=NULL)
	{
		while (fgets(line,199,file_name1)!=NULL)
		{
			
			if(afisare>=count1)
				printf("%s",line);
			afisare++;
			
		}
		count=0;  count1=0;
	}
	else perror("Eroare");
   	}
   	else perror("Eroare");
	fclose ( file_name1 );;
Posted

Why do you open the file twice (and close it only once even when opening fails)?

You should have a look at the rewind - C++ Reference[^] function.

To speed up execution you can also allocate a ring buffer with m items to store the line positions. Then you can use fseek - C++ Reference[^] with the lowest position to jump to the first line to be printed out.

Untested snippet:
C++
long int *positions = (long int *)malloc(m * sizeof(long int));
int pos = 0;
int last_pos = 0;
positions[0] = 0;
while (fgets(line, 199, file_name1) != NULL)
{
    if (++pos >= m)
        pos = 0;
    positions[pos] = ftell(file_name1);
    last_pos = pos;
    count++;
}
if (count < m || ++last_pos >= m)
    last_pos = 0;
fseek(file_name1, positions[last_pos], SEEK_SET);
while (fgets(line, 199, file_name1) != NULL)
{
    printf("%s",line);
}
free(positions);
 
Share this answer
 
Comments
Laurentiu Bobora 15-Feb-16 10:00am    
Thanks!!
If must to display last n bytes from a file, how to do ?
Jochen Arndt 15-Feb-16 10:19am    
By getting the file size, subtracting n, seeking to that position, and start printing.

To get the file size seek to the end using fseek(file_name1, 0, SEEK_END), read the position with ftell(), and rewind.
You already posted this question at tail -c command linux, implement with c[^]. Please do not repost.
 
Share this answer
 
Comments
Laurentiu Bobora 15-Feb-16 14:25pm    
it's not the same question , there was tail -c , and here tail -n

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900