Basic Structures int get function or reading from text file

57 views Asked by At

I have to create function int get(struct telephone list[ ]); ,which will load name and number from text file .The text file can be more than 5 items long but I have to load just 5 of them . But when I put instead char *fname the structure ,it does not work . Shouldn't be inside the int get function what file I want to read or the input ?

#include <stdio.h>
#include <stdlib.h>

#define MAX_ARRAY_SIZE 5

struct telephone
{
    char name[30];
    int number;

};

struct telephone list[MAX_ARRAY_SIZE];

int load(char *fname);

int main()
{
    char *fname = "BP";

    load(fname);

    int i = 0;
    int count = 0;
    for (i = 0; i < MAX_ARRAY_SIZE; i++)
    {

        printf("Name and phone is : %s\n %d\n", list[i].name,list[i].number);
        printf("%d\n",count);
        count++;
    }

    return 0;
}

int load(char *fname)
{
    FILE *fp = NULL;
    int  i = 0;

    if ((fp = fopen(fname, "r")) == NULL)
    {
        printf("Error : Unable to open for reading\n");
        return 1;
    }

    while (fscanf(fp, "%s %d", &list[i].name, &list[i].number) != EOF)
    {
        i++;
    }

    fclose(fp);
}
1

There are 1 answers

0
John Bollinger On BEST ANSWER

I think this is the actual question you're asking:

Shouldn't be inside of int get function what file I want to read or the input ?

It's a bit hard to follow your English, but I think you're asking about how the get() function you are supposed to write would determine from which file to read the data.

It's unclear precisely what your instructor expects, but inasmuch as the function's parameters do not include a file name, there are two main alternatives:

  1. Use a pre-determined file name. There are numerous variations on this, but the absolute simplest is to pass a string literal to fopen(), something like this:

    FILE *telephone = fopen("telephone.txt");
    
  2. Use a file-scope variable (sometimes misleadingly called a "global" variable) pointing to the file name to convey the data. Set the variable appropriately before calling the get() function, using data prompted from the user, from a program argument, or from some other source.