I want to implement bubble sort with writing to the file. I think that sorting is implemet good, but something wrong is with writing to file.
int main(int argc, char *argv[])
{
FILE *fp;
int tab[] = {3,5,1,2,4};
int i, j, temp;
if ((fp=fopen("test.txt", "w"))==NULL) {
printf ("Error!\n");
exit(1);
}
for(i =0; i<5;i++)
{
for(j=0; j<4; j++)
{
if(tab[j] > tab[j+1])
{
temp = tab[j+1];
tab[j+1] = tab[j];
tab[j] = temp;
}
}
}
fprintf (fp, "%d", tab);
fclose (fp);
return 0;
}
Can you help me?
Since
%dformat string instructsprintf()to print a single integer what the code tries to do is writing a pointer to an array of integers as if it was an integer.Simply loop over your array and print one
intin every iteration. You will also need to decide on a separator you want to use or else all the integers will be written side by side preventing the reader from making sense of them.