Hi,
I was trying to make a simple bubblesort program.
Read in numbers from a text file and compare them with the next line, sort in ascending order.
Now, I've found my program is able to read from the file just fine, it's when I use any write commands (fprintf, or fputs) that everything goes wrong.
I've tried using ftell and fseek and I had the same issue.
Assuming the text file contains:
1804289383 846930886 1681692777 1714636915 1957747793 424238335 719885386 1649760492 596516649
It gets stuck in an infinite loop with
846930886 846930886 8804289383 8804289383 ...
as the output to the file and 8804289383 repeating over and over
int main(void) {
int swapped;
int run_once;
// pointers
FILE *filep;
// file positions
fpos_t currpos;
fpos_t prevpos;
fpos_t nextpos;
/**
* next pos helps represent where the file pointer was
* before the switch was initiated
*/
// swap variables
unsigned long long int prev;
unsigned long long int curr;
// string inputs
char buffer[20];
// open file stream
filep = fopen("dataFile.txt","r+"); // looks for the file to open for r/w
if (filep == NULL) { // check for file
fprintf(stderr, "dataFile.txt does not exist!!\n");
return 1;
}
// bubble sort
do {
rewind(filep); // starts the pointers at the start of the file
fgetpos(filep,&currpos);
prevpos = currpos;
nextpos = currpos;
swapped = 0; // swapped = false
curr = 0;
prev = 0;
fgets(buffer, 20, filep); // need to read before loop or else it doesn't end properly
while (!feof(filep)) { // while it's not the end of the file
fgetpos(filep,&nextpos);
sscanf(buffer,"%lld",&curr); // convert to unsigned long long
printf("Prev: %lld\n",prev); // troubleshooting stuff
printf("Curr: %lld\n",curr);
if (prev > curr) {
fsetpos(filep,&prevpos); // move filep to previous
fprintf(filep,"%lld\n",curr); // print current to previous spot
fsetpos(filep,&currpos); // move filep to current
fprintf(filep,"%lld\n",prev); // print previous to current spot
printf("Swapped!\n"); // more troubleshooting
swapped = 1; // swapped = true
fsetpos(filep,&nextpos); // reset filep by moving it to nextpos
}
if (prev < curr) {
prev = curr; // no need to swap since prev will continue to be the previous value
}
// increment the postions
prevpos = currpos;
currpos = nextpos;
fgets(buffer, 20, filep);
}
} while (swapped == 1);
// close file stream
fclose(filep);
return 0;
}
Thanks you very much for your help, because I've spent over 10 hours trying to figure out how to fix this with no luck.