[英]How can I read a certain information from a line in a text file?
I'm trying to read the CIN code for patients between 1997 and 2000 dates from file patient.txt
.我正在尝试从文件patient.txt
读取 1997 年至 2000 年日期之间患者的 CIN 代码。 It mostly works well but in the specific 1981 date, which there are two of patients with this same date, it seems to display only the CIN code for the first patient, Why is that?它大多运作良好,但在特定的 1981 年日期,有两个患者具有相同的日期,它似乎只显示第一个患者的 CIN 代码,这是为什么呢?
#include <stdio.h>
#include <stdlib.h>
#include<string.h>
void main()
{
FILE *fichier;
fichier = fopen("patient.txt", "w");
if (fichier != NULL) printf("le fichie patient.txt est cree !\n");
fprintf(fichier, "voici la liste de nos patients!\n");
fprintf(fichier, "nom:Tahar prenom:Jaafer CIN:14610862 Date De Naissance:14/01/2002\n");
fprintf(fichier, "nom:Ali prenom:Khalfalh CIN:26540392 Date De Naissance:15/02/1997\n");
fprintf(fichier, "nom:Mohamed prenom:Gamadi CIN:15401256 Date De Naissance:12/12/2000\n");
fprintf(fichier, "nom:Samir prenom:Alouani CIN:11226508 Date De Naissance:7/02/1981\n");
fprintf(fichier, "nom:Haj prenom:Mohamed ali CIN:12012725 Date De Naissance:15/05/2005\n");
fprintf(fichier, "nom:Farah prenom:Bouanane CIN:12751802 Date De Naissance:18/07/1981\n");
fclose(fichier);
char sntnc[100];
int pos;
char *ptr1[50], *ptr2[50];
fichier = fopen("patient.txt", "r");
char word[8] = "/1981\n", nm_cin[5];
int c;
while ((c = getc(fichier)) != EOF)
{fgets(sntnc, 100, fichier);
if (strstr(sntnc, word) != 0)
{printf("found\n");
*ptr1 = strstr(sntnc, "CIN");
*ptr2 = strstr(sntnc, "\n");
pos = (*ptr1 - *ptr2) + 2;
fseek(fichier, pos, SEEK_CUR);
fscanf(fichier, "%s", nm_cin);
printf("CIN=%s\n", nm_cin);
}
}
}
There are two major errors.有两个主要错误。
nm_cin[5]
- The array is too short to store the 8-digit CIN. nm_cin[5]
- 数组太短,无法存储 8 位 CIN。 The fscanf()
stores beyond the end of the array, overwrites another variable, and the program ceases to behave well-defined. fscanf()
存储超出数组末尾,覆盖另一个变量,并且程序不再表现良好定义。 Make it nm_cin[9]
.使它成为nm_cin[9]
。
After fseek()
and fscanf()
the file position is in the middle of the line and the next fgets()
continues reading from there.在fseek()
和fscanf()
之后,文件 position 位于该行的中间,下一个fgets()
继续从那里读取。 This causes the program to get out of step.这会导致程序失步。 Better don't disturb the read sequence.最好不要干扰读取顺序。 You already have the whole line read as a string , as Weather Vane noted, so you can read the CIN from the sntnc
buffer.正如 Weather Vane 指出的那样,您已经将整行读取为 string ,因此您可以从sntnc
缓冲区中读取 CIN。 Change改变
pos = (*ptr1 - *ptr2) + 2; fseek(fichier, pos, SEEK_CUR); fscanf(fichier, "%s", nm_cin);
to至
sscanf(*ptr1+4, "%8s", nm_cin);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.