-2

I tried something but Resus mainly not know how to read the file line by line to compare lines between them, I get the error segmentation fault ( core dumped ). This is my function for uniq -u command

void uniq_u()
{
//  strcpy(file_name1,params[2]);
FILE *file = fopen ( file_name1, "r" );
if ( file != NULL )
{

  fgets(prev, sizeof prev,file);
  while ( fgets ( line, sizeof line, file ) != NULL ) /* read a line */
  {
 if(!strcmp(line, prev))

        printf("%s", prev);
 else 
        strcpy(prev,line);
  }
  fclose ( file );
}
}

Thanks!

msw
  • 42,753
  • 9
  • 87
  • 112
  • 1
    Debugging is a super method to find out where segmentation violations occur. You don't show how `prev` and `line` are defined (why not make them locals?), but my guess is that they are pointers without memory allocated to them. In other words, you probably have `char *line;` where you need `char line[200];` – M Oehm Jan 09 '16 at 21:39

1 Answers1

0

Please mention the declaration of "prev" and "line" variables. Regardless , I think reading this might solve your problem : Difference between char* and char[]

Community
  • 1
  • 1
Alexie Dariciuc
  • 341
  • 1
  • 3
  • 8
  • char *line; char *prev; – Laurentiu Bobora Jan 09 '16 at 22:24
  • @LaurentiuBobora try reading the answers from the link I provided , char* is read-only unless dynamically allocated and you should have also got a warning about using uninitialized pointers. Changing them into char line[200] , prev[200]; should make it work. – Alexie Dariciuc Jan 09 '16 at 22:28
  • I have changed, but not even go so :( – Laurentiu Bobora Jan 09 '16 at 22:50
  • @LaurentiuBobora have you also changed the 2nd parameter of fgets to 199 ? – Alexie Dariciuc Jan 09 '16 at 22:52
  • @LaurentiuBobora I'm glad you got it working. Don't forget to mark my answer as selected answer if it helped you solve the problem. – Alexie Dariciuc Jan 10 '16 at 07:08
  • 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 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); } – Laurentiu Bobora Jan 10 '16 at 23:09