我制作了一个名为qsort.txt的文本文件,并在文件中写入了任意多个整数(在我的例子中,准确地说是35个整数).我的目标是计算该文件中有多少个整数,将它们放入由malloc()
定义的数组中,并使用qsort()
对它们进行排序.之后,我希望将排序后的数字写入一个名为sorted.txt的文本文件中.
这是我的代码,但显然不像预期的那样工作.此外,我想更灵活的代码,所以在FILE *fa = fopen(argv[1], "r+")
是argv[1]
,这样我就可以把任何其他文本文件进行排序.无论如何,我的问题是我不知道如何计算文件中有多少个整数.
#include <stdio.h>
#include <stdlib.h>
int compare(const void *a, const void *b) {
if (*(int*)a < *(int*)b)
return -1;
else if (*(int*)a > *(int*)b)
return 1;
else
return 0;
}
int main(int argc, char **argv) {
FILE *fa = fopen(argv[1], "r+");
if (!fa)
exit(1);
FILE *fb = fopen("sortirano.txt", "w+");
long duljina, i;
long *ptr, *zapis;
long count = 0;
while (!feof(fa))
count++;
printf("%lu\n", count);
fseek(fa, 0, SEEK_END);
duljina = ftell(fa);
fseek(fa, 0, SEEK_SET);
ptr = (long *)malloc(sizeof(long));
while (!feof(fa)) {
fscanf(fa, "%lu", ptr);
count++;
}
printf("count: %lu\n", count);
for (i = 0; i < count; i++)
printf("%lu ", ptr[i]);
printf("\n");
free(ptr);
fclose(fa);
fclose(fb);
return 0;
}
EDIT:个
这是我的新代码,它更简单:
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
int compare(const void *a, const void *b) {
if (*(long*)a > *(long*)b)
return 1;
if (*(long*)a < *(long*)b)
return -1;
else
return 0;
}
int main() {
FILE *fa = fopen("qsort.txt", "r"); assert(fa != NULL);
FILE *fb = fopen("sorted.txt", "w+"); assert(fa != NULL);
long *ptr;
long save;
long count = 0;
long i;
long k;
while ((fscanf(fa, "%ld", &save)) == 1) //number of elements
prebroji++;
printf("count: %ld\n", count); //checking how many elements i have, just to make sure it works ok
ptr = (long *)malloc(count * sizeof(long)); //mallociranje
for (i = 0; i < count; i++)
fscanf(fa, "%ld", &ptr[i]);
for (i = 0; i < count; i++) //checking if numbers were saved at malloc array
printf("%ld ", ptr[i]);
qsort(ptr, count, sizeof(long), compare);
for (i = 0; i < count; i++) //checking if sorted correctly
printf("%ld ", ptr[i]);
for (i = 0; i < count; i++)
fprintf(fb, "%ld", ptr[i]);
printf("\n");
free(ptr);
fclose(fa);
fclose(fb);
return 0;
}
但它不起作用:我得到的都是打印的零.