how to use fscanf

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Norgy
    New Member
    • May 2013
    • 56

    how to use fscanf

    I am trying to read the name, phone number and address from a file
    here is the code but it doesn't work and i don't know where is the problem
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    struct PhoneBook{
    		char name[50];
    		int phoneNumber;
    		char address[50];
    } ;
    int read(struct PhoneBook user[], int n, FILE* fp);
    
    
    void main()
    {
    	//int i, j;
    	struct PhoneBook user[10];
       FILE* fp = fopen("D:\\phoneBook.txt", "r");
       int i = 0;
       int counter;
       while (!feof(fp)) {
           read(user, i, fp);
           i++;
       }
       counter = i;
    }
    
    int read(struct PhoneBook user[], int n, FILE* fp){
       //char temp;
    
       if(fp==NULL){
           printf("Error\n");
           return -1;
       }
       fscanf(fp,"%s %d %s\n", user[n].name,user[n].phoneNumber, 
             user[n].address);
    
    }
    and here is the contents of the file:
    jack 01014 jgd

    Moh 02925 Tyeu
    when i run it on dev c++, a message appear saying that the prog has stopped working and no output appears
    i want to put the name in user[n].name, the phone number in user[n].phoneNumber and the address in user[n].address
  • Banfa
    Recognized Expert Expert
    • Feb 2006
    • 9067

    #2
    As with all the scanf family of functions you need to provide pointers to the locations to store data.strings, or arrays of charcters already decompose to a pointer by to write into the int you need to dereference it

    Code:
    fscanf(fp,"%s %d %s\n", user[n].name, [B]&[/B]user[n].phoneNumber, user[n].address);

    Comment

    Working...