Я хочу найти и отобразить информацию о «контакте», но она не работает - PullRequest
0 голосов
/ 26 января 2019

Итак, у меня есть файл (это адресная книга), который содержит информацию о людях, отформатированных таким образом

———————— CONTACT ————————

Имя: Тони

Фамилия: Старк

Адрес: Малибу

Телефон: 10203044032

E-mail: tony.stark@ jarvis.com

Компания / Место работы: Старк Индастрис

————————- КОНТАКТ ————————-

Iиметь такой код:

#define MAX_VALUE_FOR_ARRAYS 1000

int main()
{

 long pos = 0; /// this will store the position of the cursor  
 char address_book_content[MAX_VALUE_FOR_ARRAYS];
 char contact_name[MAX_VALUE_FOR_ARRAYS];
 char *string_exists = NULL;
 File *show_address_book = NULL;
 show_address_book = fopen("addressBook.txt", "r");

 printf("Enter the name of the contact you want to search");
 scanf("%s", &contact_name);

 /** I want : when the user inputs a name, the program searches it in the file and if it’s found it prints the rest of the file starting from the line where that name is. So I tried the following **/

 while ( (fgets(address_book_content, MAX_VALUE_FOR_ARRAYS, show_address_book) != NULL)
 {

  if ( (string_exists = strstr(address_book_content, contact_name) != NULL)
  {

   printf("%s", address_book_content);
   pos = ftell(show_address_book);
   fseek(show_address_book, 27, pos); /// 27 in just a random number, I just want it to change the position of the cursor in the file
   printf("%s", address_book_content);

  }

 }

 return 0;

}

Когда я, например, вводю «Тони», отображается только:

Имя: Тони

Я хочу, чтобы он отображал всю информацию дляконтакт «Тони»

Так что, если вы могли бы помочь мне, спасибо

1 Ответ

0 голосов
/ 26 января 2019

in

printf(“%s”, address_book_content);
pos = ftell(show_address_book);
fseek(show_address_book, 27, pos); /// 27 in just a random number, I just want it to change the position of the cursor in the file
printf(“%s”, address_book_content);

fseek не меняет address_book_content, поэтому вы пишете два раза одно и то же

, которое необходимо прочитать в файле изпозиция, которую вы вычислили, чтобы иметь возможность написать то, что вы прочитали, изменив address_book_content, если вы все еще печатаете ее.Или просто прочитайте и распечатайте следующие строки после той, которую вы прочитали:

while ( (fgets(address_book_content, MAX_VALUE_FOR_ARRAYS, show_address_book) != NULL)
 {
  if ( (string_exists = strstr(address_book_content, contact_name) != NULL)
  {
    fputs(address_book_content, stdout); /* fputs rather printf to not write again a \n */
    /* supposing it was the firstname there are 5 lines after to read and print */
    fputs(fgets(address_book_content, MAX_VALUE_FOR_ARRAYS, show_address_book), stdout);
    fputs(fgets(address_book_content, MAX_VALUE_FOR_ARRAYS, show_address_book), stdout);
    fputs(fgets(address_book_content, MAX_VALUE_FOR_ARRAYS, show_address_book), stdout);
    fputs(fgets(address_book_content, MAX_VALUE_FOR_ARRAYS, show_address_book), stdout);
    fputs(fgets(address_book_content, MAX_VALUE_FOR_ARRAYS, show_address_book), stdout);
    break;
  }
}

Предупреждение strstr - неправильный путь, потому что он поймает имя, содержащее ожидаемую, длянапример, имя IamNotTonyAtAll совпадение Тони с использованием strstr

Конечно, каждый раз при поиске файла довольно дорого читатьдля имени ...


Полное предложение:

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

#define MAX_VALUE_FOR_ARRAYS 1000

int main()
{
  FILE * fp = fopen("addressBook.txt", "r");

  if (fp == NULL) 
    puts("cannot read addressBook.txt");
  else {
    /* use static vars to not take place into the stack */
    static char contact_name[MAX_VALUE_FOR_ARRAYS];
    printf("Enter the name of the contact you want to search : ");

    if (scanf("%s", contact_name) != 1)
      puts("invalid input");
    else {
      static char line1[MAX_VALUE_FOR_ARRAYS];
      static char line2[MAX_VALUE_FOR_ARRAYS];

       /* to have \n at the end like the read lines, it is also possible
          to read the name with fgets but in case of extra spaces at the end it is not found */
      strcat(contact_name, "\n");

      while ((fgets(line1, MAX_VALUE_FOR_ARRAYS, fp) != NULL) &&
             (fgets(line2, MAX_VALUE_FOR_ARRAYS, fp) != NULL))
      {
        if ((strcmp(line1 + /*bypass "First Name : "*/ 13, contact_name) == 0) || /* first name */
            (strcmp(line2 + /*bypass "Last Name : "*/ 12, contact_name) == 0)) { /* last name */
          /* that one */
          fputs(line1, stdout);
          fputs(line2, stdout);
          if (fgets(line1, MAX_VALUE_FOR_ARRAYS, fp) != NULL) {
            fputs(line1, stdout);
            if (fgets(line1, MAX_VALUE_FOR_ARRAYS, fp) != NULL) {
              fputs(line1, stdout);
              if (fgets(line1, MAX_VALUE_FOR_ARRAYS, fp) != NULL) {
                fputs(line1, stdout);
                if (fgets(line1, MAX_VALUE_FOR_ARRAYS, fp) != NULL) {
                  fputs(line1, stdout);
                }
              }
            }
          }
          break;
        }
        else {
          fgets(line1, MAX_VALUE_FOR_ARRAYS, fp);
          fgets(line1, MAX_VALUE_FOR_ARRAYS, fp);
          fgets(line1, MAX_VALUE_FOR_ARRAYS, fp);
          fgets(line1, MAX_VALUE_FOR_ARRAYS, fp);
        }
      }
      fclose(fp);
    }
  }

 return 0;
}

Примеры:

pi@raspberrypi:/tmp $ ./a.out
Enter the name of the contact you want to search : Tony
First Name : Tony
Last Name : Stark
Address : Malibu
Phone number : 10203044032
E-mail : tony.stark@jarvis.com
Company / Place of work : Stark Industries
pi@raspberrypi:/tmp $ ./a.out
Enter the name of the contact you want to search : Stark
First Name : Tony
Last Name : Stark
Address : Malibu
Phone number : 10203044032
E-mail : tony.stark@jarvis.com
Company / Place of work : Stark Industries
pi@raspberrypi:/tmp $ ./a.out
Enter the name of the contact you want to search : Bruno
First Name : Bruno
Last Name : Pages
Address : somewhere in France
Phone number : 123456789
E-mail : me@hiddenAddress.fr
Company / Place of work : BoUML unlimited

Предположим, addressBook.txt содержит:

First Name : Tony
Last Name : Stark
Address : Malibu
Phone number : 10203044032
E-mail : tony.stark@jarvis.com
Company / Place of work : Stark Industries
First Name : Bruno
Last Name : Pages
Address : somewhere in France
Phone number : 123456789
E-mail : me@hiddenAddress.fr
Company / Place of work : BoUML unlimited
...