【问题标题】:C copying a file into a structureC将文件复制到结构中
【发布时间】:2015-02-28 23:24:01
【问题描述】:

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

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;
}

【问题讨论】:

  • 抱歉,qsort 与从文件中读取数字有什么关系?请澄清。
  • 我不确定我是否做对了。您正在尝试将文件中的值加载到 Elements 的 userId 字段中,该字段存在于您的 elements 数组中?
  • @OldProgrammer 没什么,我不知道如何将文件读取到结构中。 qsort 是下一位
  • @RichouHunterc 我正在尝试将文件加载到我的第二列
  • 要挑剔:你的结构没有“列”。实际上,您的结构恰好包含两个值。你有一个这个结构的数组。而且您似乎想在数组中每个元素的第一个字段中加载文件数据。使用正确的术语将帮助您自行查找相关信息。

标签: c arrays file sorting structure


【解决方案1】:

不确定是否有可用的功能,但手动完成不需要太多代码。

你打开文件:

FILE *fp;
fp = fopen("myfile.txt", "r")

然后循环读取文件,一次一行,将每个int插入到struct数组中:

//looping through file and array with i as a counter
fscanf(fp,"%d", &elements[i].score);

这假设您正在从文件中读取分数。希望这足以让您入门!

哦,然后关闭文件:

fclose(fp);

【讨论】:

  • 更不用说struct Element elements[8]
  • 应该是&elements[i].score,而不是elements[i].score
【解决方案2】:

我几乎可以肯定这就是你要找的东西

#include <stdio.h>      /* printf */
#include <stdlib.h>     /* qsort */

struct Element
{
    int userId;
    int score;
};

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 -ascendingSortCompareFunction(a, b);
}

void readFromFile(const char *const filename,  struct Element **elements, size_t *count)
{
    FILE *file;
    void *auxiliary;
    int   index;
    int   score;
    char  line[128];

    if ((elements == NULL) || (count == NULL))
        return;
    *count    = 0;
    *elements = NULL;
    file      = fopen(filename, "r");
    if (file == NULL)
        return;

    index = 0;
    while (fgets(line, sizeof(line), file) != NULL)
    {
        if (sscanf(line, "%d", &score) == 1)
        {
            auxiliary = realloc(*elements, (1 + *count) * sizeof(struct Element));
            if (auxiliary == NULL)
            {
                free(*elements);
                fclose(file);

                *elements = NULL;

                return;
            }
            *elements                  = auxiliary;
            (*elements)[*count].userId = 1 + index;
            (*elements)[*count].score  = score;

            *count += 1;
            index  += 1;
        }
    }
    fclose(file);
}

int main ()
{
    size_t          count;
    size_t          n;
    struct Element *elements;
    size_t          size;

    elements = NULL;
    size     = sizeof(struct Element);
    count    = 0;

    readFromFile("/home/iharob/file.txt", &elements, &count);
    if ((elements != NULL) && (count > 0))
    {
        qsort(elements, count, size, 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, size, descendingSortCompareFunction);
        printf ("UserID\tScore (Descending Sort)\n");

        for (n = 0 ; n < count ; n++)
            printf ("%d\t%d\n", elements[n].userId, elements[n].score);

        free(elements);
    }
    getchar();

    return 0;
}

【讨论】:

  • 在这一行之后:'*elements = NULL;'需要有一行:'*count = 0;'
  • @user3629249 哇,这是一个非常愚蠢的错误。虽然count是在main()中初始化的,所以没有错误,但最好是在readFromFile()中初始化。
猜你喜欢
  • 2012-02-25
  • 1970-01-01
  • 2020-10-22
  • 2011-12-13
  • 1970-01-01
  • 2011-10-13
  • 1970-01-01
  • 1970-01-01
  • 2016-11-19
相关资源
最近更新 更多