C 将文件复制到结构中

标签 c arrays file sorting structure

好的,所以我有一个包含整数的文件,例如:

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/

相关文章:

C 标准库函数 'strncpy' 不起作用

c - XML -> C 解析器生成器

c - Ruby sqlite3 gem 无法在 WSL 上编译

java - 如何从字符串中进行插值搜索

c++ - 使用类 static const 整数初始化二维数组

javascript - 将具有父/子关系的对象数组转换为嵌套对象数组

c - Valgrind 报告可能的堆栈溢出 - 这是什么意思?

xml - 批量更新xml文件

java - Android 列出可以查看未知文件的应用程序

php - PHP中的多个文件上传 - 重命名文件