#1
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Sep 2003
    Location
    NYC
    Posts
    92
    Rep Power
    12

    Reading from Files


    I am doing a project in C. This program is reading from a file that contains first and last name and a phone nuber. I dont know how many records will the file have.

    My question is: How do i catch the end of file?

    PHP Code:
        FILE pFile;
        
    int i;
        
    Pb_Rec malloc(31);
        
    pFile fopen ("Pbook.dat","r");
        while(
    not end of file){
            
    fscanf(pFile"%s"Pb_Rec[i].lastName);
            
    fscanf(pFile"%s"Pb_Rec[i].firstName);
            
    fscanf(pFile"%s"Pb_Rec[i].number);
            
    printf("%s\t%s\t%s\t pos%d\n"Pb_Rec[i].lastNamePb_Rec[i].firstNamePb_Rec[i].numberi);
            
    recCount();  //reallocates more space if needed and increments variable i
        
    }

        
    fclose(pFile); 
  2. #2
  3. Banned ;)
    Devshed Supreme Being (6500+ posts)

    Join Date
    Nov 2001
    Location
    Woodland Hills, Los Angeles County, California, USA
    Posts
    9,607
    Rep Power
    4247
    Use feof(). Simply replace:
    Code:
    while(not end of file){
    with
    Code:
    while(!feof(pFile)){
    Up the Irons
    What Would Jimi Do? Smash amps. Burn guitar. Take the groupies home.
    "Death Before Dishonour, my Friends!!" - Bruce D ickinson, Iron Maiden Aug 20, 2005 @ OzzFest
    Down with Sharon Osbourne

    "I wouldn't hire a butcher to fix my car. I also wouldn't hire a marketing firm to build my website." - Nilpo
  4. #3
  5. Contributing User
    Devshed Supreme Being (6500+ posts)

    Join Date
    Jan 2003
    Location
    USA
    Posts
    7,143
    Rep Power
    2222
    Word of caution:
    The end-of-file condition won't be set until you try reading the file and fail. Therefore, as your program is currently written, your last results will be wrong. Play around with it to figure out how best to structure your read routine.
  6. #4
  7. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Sep 2003
    Location
    NYC
    Posts
    92
    Rep Power
    12
    Thank You
    MrZenka

IMN logo majestic logo threadwatch logo seochat tools logo