-2

I'm trying to search a file containing information on a group of people, for example: their first name, last name and ID.

I'm prompting the user to enter their ID code. The program should search the text file and ensure that their code matches the one within the file so that the program can continue by comparing the string from the file and the variable inputted by the user.

I'm not sure how to implement this. Below is a snippet of the code:

#include <stdio.h>
#include <conio.h>
#include <string.h>

typedef struct record {
  char (fname[3])[20];
  char (lname[3])[20];
  int code[3];
} information;

int main (void) {
  char ffname[20], flname[20];
  int fID, i;
  FILE *kfile;

  if ((kfile = fopen("C:\\Users\\Student\\Downloads\\information.txt","r")) == NULL) {
    perror("Error while opening file");
  } else {
    printf("%-20s %-20s %s\n", "First Name", "Last Name", "ID");
    fscanf(kfile, "%19s %19s %d", ffname, flname, &fID);
    printf("\n");
    while (!feof(kfile)) {
      printf("%-20s %-20s %04d\n", ffname, flname, fID);
      fscanf(kfile, "%19s %19s %d", ffname, flname, &fID);
    }
    fclose(kfile);
  }

  information info;
  for (i = 0; i < 3; i++) {
    printf("Please enter your ID.");
    scanf("%04d", &info.code);
  }
  getch();
  return 0;
}
fenceop
  • 1,439
  • 3
  • 18
  • 29
  • How big is your file? How many records in it. How is the text formatted? Do you control the formatting of the texte or is it a file that is given to you by a 3rd party ? – Félix Cantournet Feb 25 '15 at 20:29
  • So you read the file and display it and once it's over you ask for the ID ? three times reading the same ID ?? No very user friendly ! And where do you actually search for the data ? – Christophe Feb 25 '15 at 20:33

1 Answers1

0

I'm not sure I understand your problem, but you can try this:

typedef struct record {
  char *fname;
  char *lname;
  int code;
} information;

int main (void) {
  char ffname[28], flname[28];
  int fID, i, id_;
  information array[3];
  FILE *kfile;
  i = 0;

  if ((kfile = fopen("C:\\Users\\Student\\Downloads\\information.txt","r")) == NULL) {
    perror("Error while opening file");
  } else {
    while (!feof(kfile)) {
      fscanf(kfile, "%s %s %d", ffname, flname, &fID);
      array[i].fname = strdup(ffname);
      array[i].lname = strdup(flname);
      array[i].code = fID;
      i++;
    }
    fclose(kfile);
  }

  printf("Please enter your ID: ");
  scanf("%d", &id_);
  for (i = 0; i < 3; i++) {
    if (array[i].code == id_) {
      // print the record
      printf("%s %s \n", array[i].fname, array[i].lname);
    }
  }
  return 0;
}
fenceop
  • 1,439
  • 3
  • 18
  • 29
Anastasis
  • 192
  • 1
  • 2
  • 12