c - 我使用哪个函数从文件中读取文本?

标签 c algorithm file dynamic struct

这是我想从文件中以这种格式加载到我的终端的文本

                                    nom                  : avatar
                                    type                 : Science_fiction
                                    l'annee de sortie    : 2012
                                    duree                : 120 minutes
                                    numero de reference  : 9

                                    nom                  : dark_knight
                                    type                 : Action
                                    l'annee de sortie    : 2008
                                    duree                : 124 minutes
                                    numero de reference  : 8

我厌倦了使用 sscanf,它可以工作,但每个输入都只占一行

avatar Science_fiction 2012 120 9
dark_knight Action 2008 124 8

这是我的代码

   #include<stdlib.h>
   #include<stdio.h>
   #include<string.h>
   #include "structure_film.h"

   void load(struct film **head,struct film **current, FILE ** fichier,struct film **tail)

         char donnesDuFilm[255];

   struct film *premierfilm;premierfilm=(struct film*)malloc(sizeof(struct film));

    printf("le programme est en train de charger le catalogue depuis le fichier     catalogue\n");


   if (fgets(donnesDuFilm,255,*fichier)&&(strcmp(donnesDuFilm,"")))
    {


      sscanf(donnesDuFilm,"nom %s  type %s l'annee de sortie %d duree %d numero de reference %d\n",&premierfilm->nom,&premierfilm->typeFilm,&premierfilm->dateSortie,&premierfilm->duree,&premierfilm->id);

      printf("%s %s %d %d %d\n",premierfilm->nom,premierfilm->typeFilm,premierfilm->dateSortie,premierfilm->duree,premierfilm->id);


     *head=premierfilm;
    }
    while (fgets(donnesDuFilm,255,*fichier)&&(strcmp(donnesDuFilm,"")))
    {  
          struct film *nouveauFilm;

        nouveauFilm=(struct film*)malloc(sizeof(struct film));premierfilm->next=nouveauFilm;


        sscanf(donnesDuFilm,"nom %s  type %s l'annee de sortie %d duree %d numero de reference %d\n",&nouveauFilm->nom,&nouveauFilm->typeFilm,&nouveauFilm->dateSortie,&nouveauFilm->duree,&nouveauFilm->id);

        printf("%s %s %d %d %d\n",nouveauFilm->nom,nouveauFilm->typeFilm,nouveauFilm->dateSortie,nouveauFilm->duree,nouveauFilm->id);


        premierfilm=nouveauFilm;
        nouveauFilm->next=NULL;



    }

*current=premierfilm;*tail=premierfilm;


}

最佳答案

fscanf 是用于读取文本文件的函数。考虑到这是一个非常常见的功能,谷歌上应该有很多关于它的信息。但首先您需要创建一个文件指针,并使用 fopen。

char stringname[15]
FILE *filename = fopen("filelocation", r);
fscanf(filename, "%s", stringname);

关于c - 我使用哪个函数从文件中读取文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20924512/

相关文章:

c -\b 是如何实现的?

c - 返回语句在哪里保存它的数据?

algorithm - 获取图像变化算法

c - 我的 execvp 使用有什么问题?

java - 在 Java 中使用递归的主要因素

algorithm - 将弓箭手放在墙上

java - 如何列出当前目录中的文件?

c#二进制序列化到文件逐行或如何分离

java - 通过套接字将 Java 文件对象发送到服务器

c - 为什么下面代码中的 for 循环不作为无限循环运行(我在 -1 之后继续作为 1 2 3...-3 -2 -1)?