Click here to Skip to main content
15,885,036 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I try to implement uniq -i command, you must display the contents of a file without duplicate lines
exemple :
I have
I have
bad
you
you

I must display:
I have
bad
you

This is my function

Objective-C
void uniq_i()
{
   //file_name1=fopen(params[2],"r");
   
   if ( file_name1 != NULL )
   {
      
      fgets(prev1,199,file_name1);
      while ( fgets ( line, 199, file_name1 ) != NULL ) /* read a line */
      {
	
	if(!strcmp(prev1,line))
	{
	
		printf("%s", prev1);
		
		
	}
	else if(strcmp(prev1,line))
	{

		printf("%s",line);
		
		
	}
	
	strcpy(prev1,line);
      }
      
   }
   else perror("Eroare");
fclose ( file_name1 );
}
Posted
Comments
Garth J Lancaster 10-Jan-16 20:32pm    
what is your code doing/not doing ? have you stepped through your code with a debugger/breakpoints etc ?

You also only seem to be interested in consecutive duplicate lines - what happens if you have

I have
I must
I have

???
Laurentiu Bobora 11-Jan-16 3:42am    
It now correctly displays up to the first two lines then no longer works, if I have:
Jhon
Jhon
have
apple
apple

Print:
Jhon
have
apple
apple


I will try to do troubleshooting

how about like this:
uniq -f 1 -c file | awk '{print $2}'
 
Share this answer
 
A possible solution would be:
// Get and print first line
if (fgets(prev1, 199, file_name1) != NULL)
    printf("%s",prev1);
while (fgets(line, 199, file_name1) != NULL)
{
    // Print if not identical to previous one
    if (strcmp(line, prev1))
        printf("%s",line);
    strcpy(prev1, line);
}
 
Share this answer
 
Comments
Laurentiu Bobora 11-Jan-16 5:50am    
and if you just want single lines ?
Jochen Arndt 11-Jan-16 6:10am    
What do you mean by single lines?
Print only those lines that are not duplicates?

That is different from your initial question.
It may look like this (untested):

int dup = -1;
fgets(prev1, 199, file_name1);
while (fgets(line, 199, file_name1) != NULL)
{
 // Mark as duplicate to be not printed later
 if (0 == strcmp(line, prev1))
  dup = 1;
 else
 {
  if (dup <= 0)
   printf("%s", prev1);
  strcpy(prev1, line);
  dup = 0;
 }
}
// Print last line if not identical to previous one
if (0 == dup)
 printf("%s", prev1);
Laurentiu Bobora 11-Jan-16 6:21am    
Thanks !!! :)

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