繁体   English   中英

添加项目排序到文件中 c

[英]Add item sorted into a file in c

我需要获取一个.txt 文件,并检查其中存在的分数,如果我的分数在前 5 名之列,请以正确的顺序将我的分数和我的名字添加到文件中。 但是按照我的方式,append 只在末尾添加。 有没有办法检查文件中的点,进行比较?

例子:如果我的积分大于40,就把我的名字和积分数放在前面。 留下列表的 rest 再次排序。

佩德罗=40
joao=32
克劳迪奥=10
joao=2
瑞克=0

#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>

int main() {

    char teste[1000], nome[20];
    int meuPonto=0;
    FILE *pontos;
    pontos = fopen("dados.txt", "r");

    if(pontos == NULL){
        exit(1);
    }

    printf("Pontuacao atual:\n");
    while(fgets(teste, 1000, pontos)){
        printf("%s\n", teste);
    }

    printf("Digite seu nome e seus pontos:\n");
    scanf("%s %i", nome, &meuPonto);

    fclose(pontos);
    pontos = fopen("dados.txt", "a");

    fprintf(pontos, "\n%s\n%d", nome, meuPonto);

    fclose(pontos);
}

该文件可以从零开始,但您必须保存写入的乐谱。

用空行初始化数组 [MAX_SCORE]。

根据你的分数,array[your_score] 将你的行添加到数组中。

将每一行读入数组[line_score]。 如果你得到重复项(位置不为空),append LF 之后的行。

最后,将数组(向后)打印到新文件(或覆盖旧文件)。 (跳过空行)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM