简体   繁体   中英

How can I read data from file?

I'm trying to create phone book which has five function in c. I have formed just first function which takes and saves in file people's knowledge. However, I cannot succeed the second function which search just a person's (Not all people) knowledge from file.

To run this function (""display() function"") I want to a name from user to search and to display that name's knowledge on the screen. I wrote something but it didn't work. The problem is display() function. How can I read just one line and print it on the screen? Thanks in advance.

#include <stdio.h>
#include <stdlib.h>     // "stdlib" library contains of exit() and malloc function                        
#include <Windows.h>   // "Windows" library contains of Sleep() function
#include <string.h>   // "string" library contains of strcmp() function

struct personKnowledge
{
    char number[16];
    char name[16];
    char surname[16];
};

void newRecord();
void display();
void deletE();
void add();
void update();

FILE *ptrFILE;

int main()
{
    int choice;
    printf("\n\t\t *-* Phone Book Program *-*");
    do
    {
        printf("\n\n\t\t 1) New record");   // The options are being presented to user
        printf("\n\n\t\t 2) Display person knowledge");
        printf("\n\n\t\t 3) Delete someone");
        printf("\n\n\t\t 4) Add new person");
        printf("\n\n\t\t 5) Update person knowledge");
        printf("\n\n\t\t 6) Exit");
        printf("\n\n\nEnter your choice: ");
        scanf("%d", &choice);
        switch (choice)
        {
        case 1:
        {
            newRecord();
            break;
        }
        case 2:
        {
            display();
            break;
        }
        case 3:
        {
            break;
        }
        case 4:
        {   
            break;
        }
        case 5:
        {
            break;
        }
        case 6:
        {
            printf("\nWorking has been completed.\n");
            exit(0);
            break;
        }
        default:
        {
            printf("\nWrong entry! The program has been terminated.\n");
        }
        }   
    } while (choice >=1 && choice <=6 );
    return 0;
}

void newRecord()
{
    system("cls");   // Screen is being cleaned
    if ((ptrFILE = fopen("Phone Book.txt", "w")) == NULL)
    {
        printf("The file couldn't open\n");
    }
    else
    {          
        struct personKnowledge *p;   // p means person
        p = (struct personKnowledge *)malloc(sizeof(struct personKnowledge));   // Memory is being allocated
        fflush(stdin);
        printf("\n\nDetermine person name: ");   // User is entering the person's knowledge and they are being saved in file
        gets(p->name);
        printf("Determine %s's surname: ", p->name);
        gets(p->surname);
        printf("Determine %s's number: ", p->name);
        gets(p->number);
        fprintf(ptrFILE, "Name\t\t\t\tSurname\t\t\t\t\tNumber\n");
        fprintf(ptrFILE, "--------\t\t   ----------------\t\t\t---------------------\n");
        fprintf(ptrFILE, "\n%s%33s%38s\n", p->name, p->surname, p->number);
        fclose(ptrFILE);
        free(p);
        printf("Please wait, information is saving to file..\n");
        Sleep(1000);
        printf("*-* Saving operation has been completed. *-*");
    }
    fclose(ptrFILE);
}

void display()
{
    struct personKnowledge *s;   // s means searching
    char name[16];
    if ((ptrFILE = fopen("Phone Book.txt", "r")) == NULL)
    {
        printf("The file couldn't open\n");
    }
    else
    {
        fseek(ptrFILE, 0L, SEEK_SET);
        printf("Express name which you search: ");
        gets(s->name);
        while (!feof == NULL)
        {
            fscanf(ptrFILE,"%s", &name);
            if (strcmp(s->name, name) == 0)
            {
                printf("qawsdsdf");
            }
        }
    }
    fclose(ptrFILE);
}

In answer to one of your questions, I recommend rewriting this loop in display()

while (!feof == NULL)                   // wrong way to use feof
{
    fscanf(ptrFILE,"%s", &name);        // might overflow the string space
    if (s->name == name)                // wrong way to compare strings
    {
        printf("qawsdsdf");             // missing newline?
    }
}

with this

while (fgets(name, sizeof(name), ptrFILE) != NULL)  // safer way to read to a small buffer
{
    name [ strcspn(name, "\r\n") ] = 0; // remove trailing newline etc
    if (strcmp(s->name, name) == 0)     // compare the strings
    {
        printf("qawsdsdf\n");           // added newline
    }
}

EDIT in any case your posted code does not even compile properly:

while (!feof == NULL)

is rubbish, it should have been

while (!feof(ptrFILE))

although as I said is not the way to use feof anyway. This would not have happened if you had compiler warnings enabled and dealt with them.

My solution was to change how the file is formatted

fprintf(ptrFILE, "\n%s%33s%38s", p->name, p->surname, p->number);

Because if you're using a program to retrieve information, there's no need to fill it with a bunch of junk headers every time you write to it. I then edited the display function to be able to retrieve said information.

void display()
{
    struct personKnowledge s;   // s means searching
    char name[16];
    char sname[16];
    char number[16];
    char surname[16];
    if ((ptrFILE = fopen("Phone Book.txt", "r")) == NULL)
    {
        printf("The file couldn't open\n");
    }
    else
    {
        printf("Express name which you search: ");
        scanf("%s", &sname);
        do
        {
            fscanf(ptrFILE,"%s%33s%38s", &name, &surname, &number);
            if (strcmp(sname, name) == 0)
            {
                printf("%s %s %s", name, surname, number);
            }
        }
        while (strcmp(sname, name) != 0);
    }
}

PS I'm still new to c myself and I don't think I could give you a good explanation as to why my code works and yours doesn't. But I can say that those headers you were writing to the file every time was a major part of the problem when I was troubleshooting your code.

I think these minor changes will solve your problem

  • Allocate memory for storing personKnowledge s = (struct personKnowledge *)malloc(sizeof(struct personKnowledge));
  • Make file pointer reach the starting location of data. A simple trick has been used to achieve this fscanf(ptrFILE, "Name\\t\\t\\t\\tSurname\\t\\t\\t\\t\\tNumber\\n"); fscanf(ptrFILE, "--------\\t\\t ----------------\\t\\t\\t---------------------\\n"); fscanf(ptrFILE, "Name\\t\\t\\t\\tSurname\\t\\t\\t\\t\\tNumber\\n"); fscanf(ptrFILE, "--------\\t\\t ----------------\\t\\t\\t---------------------\\n");
  • Make change in while loop. while (!feof(ptrFILE))
  • Scanning one row of data. fscanf(ptrFILE, "\\n%s%33s%38s\\n", s->name, s->surname, s->number)
  • Make change in string comparison. if (strcmp(name,s->name) == 0)

The modified display function

    void display(){
      struct personKnowledge *s;   
      s = (struct personKnowledge *)malloc(sizeof(struct personKnowledge));   // Memory is being allocated for s
      fflush(stdin);

      char name[16];
      if ((ptrFILE = fopen("Phone Book.txt", "r")) == NULL)
      {
      printf("The file couldn't open\n");
      }
      else
      {
      fseek(ptrFILE, 0L, SEEK_SET);
      printf("Express name which you search: ");
      scanf("%s",name);     //the name you want to retrieve

      fscanf(ptrFILE, "Name\t\t\t\tSurname\t\t\t\t\tNumber\n");
      fscanf(ptrFILE, "--------\t\t   ----------------\t\t\t---------------------\n");   //when we read the file for first time we need to start from the first location of person data, this is a trick to make ptrFILE reach there
      fflush(stdin);

      while (!feof(ptrFILE))
      {
      fscanf(ptrFILE, "\n%s%33s%38s\n", s->name, s->surname, s->number);//same format as fprintf used in newRecord
        if (strcmp(name,s->name) == 0)   //comparison
        {
            printf("qawsdsdf");
        }
      }}fclose(ptrFILE);}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM