hi i have encountered a problem while trying to implement bubble sort in my work on a file with many records in C.
I have to ONLY modify my file and not use any temp files doing this. whenever i try to swap two lines in my file i manage to write the second line instead of the first one successfully, but when i try to write the first line instead of the second one it seems to override lines after the second one. i know that it is because the length of the lines are not identical, but is there a way maybe by padding the lines with empty chars or something to do this with success?
here is the code: (can't seem to upload the variable declaration for some reason...) the relevant part is in the if condition
for(j=0; j<linesNum-1; j++)
{
for(k=0; k<linesNum-j-1; k++)
{
getline(&line1, &len, fp);
pos = ftell(fp);
getline(&line2, &len, fp);
int i;
char *tmp1 = (char*)malloc(sizeof(char)*strlen(line1));
char *tmp2 = (char*)malloc(sizeof(char)*strlen(line2));
strcpy(tmp1, line1);
strcpy(tmp2, line2);
token1 = strtok(tmp1, del);
for(i=0; i<field; i++)
{
token1 = strtok(NULL, del);
}
token2 = strtok(tmp2, del);
for(i=0; i<field; i++)
{
token2 = strtok(NULL, del);
}
if(strcmp(token1, token2) > 0)
{
fseek(fp, -(strlen(line1)+strlen(line2)), SEEK_CUR);
fputs(line2, fp);
//fsetpos(fp, &pos);
fputs(line1, fp);
}
fsetpos(fp, &pos);
free(tmp1);
free(tmp2);
}
}
}
from this file:
GNY1MJS2X,Mulan,Tony Bancroft,88,Harvey Fierstein,USA,7.5,Adventure
A1F9ENILS,Tropic Thunder,Ben Stiller,121,Steve Coogan,USA,7,Action
3YRMEJM1Y,The Departed,Martin Scorsese,151,Matt Damon,USA,8.5,Crime
NQMNMMOMR,The Girl with the Dragon Tattoo,David Fincher,158,Goran Visnjic,USA,7.8,Crime
FT2ULUNQ5,Die Hard with a Vengeance,John McTiernan,128,Aldis Hodge,USA,7.6,Action
I seem to get this:
A1F9ENILS,Tropic Thunder,Ben Stiller,121,Steve Coogan,USA,7,Action
GNY1MJS2X,Mulan,Tony Bancroft,88,Harvey Fierstein,USA,7.5,Adventure
YRMEJM1Y,The Departed,Martin Scorsese,151,Matt Damon,USA,8.5,Crime
NQMNMMOMR,The Girl with the Dragon Tattoo,David Fincher,158,Goran Visnjic,USA,7.8,Crime
FT2ULUNQ5,Die Hard with a Vengeance,John McTiernan,128,Aldis Hodge,USA,7.6,Action
which has an empty line between the first and the second line... and it also ruin the next lines.
Also, I sorted by one field delimited by comma, say the first field which is the movie ID.
sorry for the messy way to write the files