Thread: fscanf

    #1
  1. No Profile Picture
    Junior Member
    Devshed Newbie (0 - 499 posts)

    Join Date
    Sep 2003
    Posts
    4
    Rep Power
    0

    fscanf


    i have a problem with fscanf(), i am currently using the code

    fscanf(file, "%[^\n]%*c", string);

    to read in a file line by line. this works fine until it hit's a spot in the paragraph where there are 2 '\n', for example

    " Automatically parse URLs: automatically adds and around internet addresses.
    Email Notification: emails sent to you whenever someone replies. Only registered users are eligible.

    Disable Smilies in This Post
    Show Signature: include your profile signature. Only registered users may have signatures."

    when it gets to eligible, fscanf gets stuck there and starts looping. i have no idea how to fix this because the next line is just a '\n' and shouldn't the code just automatically skip it and continue on to the next paragraph since it's suppose to only read up to '\n'? can anyone tell me what is wrong please? sorry if this was posted before but i already did a search and no one seemed to have a problem like this from what i found.
  2. #2
  3. No Profile Picture
    Dinesh_P_V
    Devshed Newbie (0 - 499 posts)

    Join Date
    Aug 2003
    Location
    India
    Posts
    259
    Rep Power
    0

    fscanf


    This works fine for me

    #include<stdio.h>
    int main()
    {
    char string[100];
    FILE *fd=fopen("test16.c","r");
    while(!feof(fd))
    {
    fscanf(fd, "%s", string);
    printf("%s",string);
    }
    }

    -Murugesan
  4. #3
  5. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Sep 2003
    Posts
    68
    Rep Power
    11
    If you're reading a file line by line then fscanf will cause you more grief than more suitable functions:
    Code:
    while (fgets(string, sizeof string, file) != NULL) {
      if (string[0] == '\n')
        continue;
      /* Work with string */
    }
    >while(!feof(fd))
    Bad idea. feof only flags the end of file *after* your input function has failed. This results in processing the last line in the file twice.
  6. #4
  7. No Profile Picture
    Junior Member
    Devshed Newbie (0 - 499 posts)

    Join Date
    Sep 2003
    Posts
    4
    Rep Power
    0
    ya i noticed fscanf is more trouble than it's worth reading a file line by line. that's why i gave up and used it to read character by character instead, but thanx for the help. :)
  8. #5
  9. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Sep 2003
    Posts
    68
    Rep Power
    11
    >that's why i gave up and used it to read character by character instead
    If you're reading character by character then fgetc is easier than fscanf. ;)

IMN logo majestic logo threadwatch logo seochat tools logo