如何从文件中读取数据?

时间:2015-07-01 16:05:57

标签: c

我正在尝试创建具有五种功能的电话簿。我已经形成了第一个功能,它记录了人们的知识。但是,我无法成功从文件中搜索一个人(不是所有人)知识的第二个功能。

要运行此功能(“”display()function“”)我想要用户名来搜索并在屏幕上显示该名称的知识。我写了一些东西,但它没有用。问题是display()函数。如何只阅读一行并将其打印在屏幕上?提前谢谢。

#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);
}

3 个答案:

答案 0 :(得分:2)

在回答您的一个问题时,我建议您在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?
    }
}

用这个

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
    }
}

编辑在任何情况下,您发布的代码甚至无法正确编译:

while (!feof == NULL)

是垃圾,应该是

while (!feof(ptrFILE))

虽然正如我所说的那样not the way to use feof无论如何。如果您启用并处理了编译器警告,则不会发生这种情况。

答案 1 :(得分:0)

我的解决方案是更改文件的格式化方式

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

因为如果你使用程序来检索信息,那么每次写入时都不需要用一堆垃圾标题来填充它。 然后,我编辑了显示功能,以便能够检索所述信息。

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);
    }
}

P.S。我自己还是新手,我认为我不能给你一个很好的解释,为什么我的代码工作而你的代码不工作。但我可以说,当我对代码进行故障排除时,每次写入文件的那些标题都是问题的主要部分。

答案 2 :(得分:0)

我认为这些微小的变化将解决您的问题

  • 分配用于存储personKnowledge s = (struct personKnowledge *)malloc(sizeof(struct personKnowledge));
  • 的内存
  • 使文件指针到达数据的起始位置。已经使用了一个简单的技巧来实现这个fscanf(ptrFILE, "Name\t\t\t\tSurname\t\t\t\t\tNumber\n"); fscanf(ptrFILE, "--------\t\t ----------------\t\t\t---------------------\n");
  • 在while循环中进行更改。while (!feof(ptrFILE))
  • 扫描一行数据。fscanf(ptrFILE, "\n%s%33s%38s\n", s->name, s->surname, s->number)
  • 更改字符串比较。if (strcmp(name,s->name) == 0)

修改后的显示功能

    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);}