我正在尝试制作一个简单的冒泡排序程序。
从文本文件中读入数字并与下一行进行比较,按升序排序。
现在,我发现我的程序能够很好地读取文件,但当我使用任何写入命令(fprintf 或 fputs)时,一切都出错了。
我试过使用 ftell 和 fseek,但我遇到了同样的问题。
假设文本文件包含:
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;
非常感谢您的帮助,因为我已经花了 10 多个小时试图弄清楚如何解决这个问题,但没有成功。
最佳答案
您交换两个相邻字符的代码有缺陷。请注意,如果您有两个数字 1 和 234,它们最初在文件中显示为 1\n234\n
,但如果交换,1 不会从文件中的索引 2 开始(其中 234最初开始),但在索引 4 处。
因此,如果您交换两个数字 prev 和 curr,prev 最初是文件中两个数字中较早的一个,则将 curr 放在 prev 的位置,并在写完 curr 后将 prev 放在换行符之后。请注意,这是一个本地更改(因为 len(prev) + len(curr) == len(curr) + len(prev)。
关于C文件指针读写问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1529643/