这是我想从文件中以这种格式加载到我的终端的文本
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/