Q:
Hi, i am new to C prog. need help on creating an array of structures.i
need to get the data in a text file print them out on the screen. how
should i go about doing the coding?? Please advice. Thank you.
Here is how the data in the text file looks like:
123456D , john david , 1234567 , m
234567F , kim steven , 2345678 , v
543321B , sam kings , 6546453 , m
Here's my coding:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct
{
char name[70];
int num;
long int tel;
}phone;
int main()
{
char name[70];
int i;
phone people[8];
FILE *fptr;
fptr = fopen("c:/c/phone1.txt", "r");
printf("Attempting to open file...\n");
if (fptr == NULL)
{
printf("Error Opening File - Program Aborting\n");
exit(-1); /*Exit the program right now*/
}
printf("File opened.\n");
for(i=0;i<8;i++)
{
fgets(people[i].name,70,fptr);
fgetc(fptr);
fgetc(fptr);
fscanf(fptr,"%d",&people[i].num);
fscanf(fptr,"%ld",&people[i].tel);
//while(getchar()!='\n');
}
fclose(fptr);
printf("Enter name: ");
fgets(name,70,stdin);
i=0;
while(strcmp(people[i].name,name)&&i<8)
{
i++;
}
if(i<10)
{
printf("phone num is %ld",people[i].tel);
}
else
printf("member not found!");
getchar();
}
A:
This is a complex issue. You have to read the line using fgets and then
you have to analyze the line to get the records from it.
This is a complex programming issue by itself.
regards,
Peter
[ back to toc ]