好的,所以我有一个包含整数的文件,例如:
14
22
82
53
61
74
47
95
我想将其复制到我的结构中,问题是我的结构有 2 列,而且我不知道如何将文件复制到其中一列中。
我的问题是:是否有像 qsort 这样快速简单的功能可以自动复制我的文件?
#include <stdio.h> /* printf */
#include <stdlib.h> /* qsort */
struct Element
{
int userId;
int score;
};
struct Element elements[] = {
{1, 13},
{2, 9},
{3, 13},
{4, 19},
{5, 8},
{6, 11},
{7, 14},
{8, 17},
};
int ascendingSortCompareFunction (const void * a, const void * b)
{
return (((struct Element *)a)->score - ((struct Element *)b)->score);
}
int descendingSortCompareFunction (const void * a, const void * b)
{
return ((struct Element *)b)->score) - (((struct Element *)a)->score;
}
int main ()
{
int n;
int count;
count = sizeof(elements) / sizeof(elements[0]);
qsort(elements, count, sizeof(elements[0]), ascendingSortCompareFunction);
printf ("UserID\tScore (Ascending Sort)\n");
for (n = 0 ; n < count ; n++)
printf ("%d\t%d\n", elements[n].userId, elements[n].score);
qsort(elements, count, sizeof(elements[0]), descendingSortCompareFunction);
printf ("UserID\tScore (Descending Sort)\n");
for (n = 0 ; n < count ; n++)
printf ("%d\t%d\n", elements[n].userId, elements[n].score);
getchar();
return 0;
}
最佳答案
不确定是否有可用的功能,但手动执行此操作不需要太多代码。
您打开文件:
FILE *fp;
fp = fopen("myfile.txt", "r")
然后循环读取文件,一次一行,并将每个 int 插入到结构体数组中:
//looping through file and array with i as a counter
fscanf(fp,"%d", &elements[i].score);
这假设您正在从文件中读取分数。希望这足以让您开始!
哦,然后关闭文件:
fclose(fp);
关于C 将文件复制到结构中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27745379/