Like Tree1Likes

Using fscanf to read text from a file.

This is a discussion on Using fscanf to read text from a file. within the C Programming forums, part of the General Programming Boards category; Code: void main(void){ #include <stdio.h> #include <stdlib.h> #include <string.h> #define MAXSIZE 256 struct member_node{ char fn[MAXSIZE]; char ln[MAXSIZE]; double numb; ...

  1. #1
    Registered User
    Join Date
    Mar 2012
    Posts
    61

    Using fscanf to read text from a file.

    Code:
     void main(void){
     
     
     #include <stdio.h>
     #include <stdlib.h>
     #include <string.h>
    
     
     #define MAXSIZE 256
     
      
    struct member_node{
        char fn[MAXSIZE];
        char ln[MAXSIZE];
        double numb;
        struct member_node *next;
    };
    
    
    
     FILE *file1 = NULL;
     char fname[MAXSIZE];
     
     struct member_node *current;
     struct member_node *head;
     
     head = (struct member_node *)malloc(sizeof(struct member_node));
     current = head;
     
     while(file1 == NULL){
        printf("Input file name:");
        scanf("%s",fname);
        if((infile = fopen(fname, "r")) == NULL) {
            printf(file not found!\n");
    
     }
     }
    Everything above works.

    I tried to write the code to scan the files from the text using a for and while loop, but it crashes when it reaches this part.

    Code:
     
     while(fscanf(infile,"%s %s %lf",current)!=EOF)  //while loop
     {
        current = current->next;
        }
        
     for(current = head;current!= NULL;current=current->next){ //for loop
        fscanf(infile,"%s %s %lf",current);
      }

  2. #2
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,467
    scanf doesn't magically know how your struct is organized. You must provide the individual parts to assign to:
    Code:
    fscanf(infile, "%s %s %lf", current->fn, current->ln, current->numb)
    Also, don't simply check for EOF. scanf returns the number of items successfully scanned. You asked for 3 things (red, green & blue below), meaning if it got everything correctly, it returns 3. If you get anything other than 3, there is a problem, thus:
    Code:
    while (fscanf(..., "%s %s %lf", ...) == 3)
        // successful scan, do something

  3. #3
    Registered User
    Join Date
    Mar 2012
    Posts
    61
    What if I don't know the number of items that need to be scanned? Shouldn't I use EOF then?

  4. #4
    Registered User
    Join Date
    May 2012
    Location
    Arizona, USA
    Posts
    383
    Can you give an example of when you wouldn't know how many items need to be scanned? I can't think of any such situation.

  5. #5
    Registered User
    Join Date
    Jun 2011
    Posts
    2,292
    As anduril462 points out, "fscanf()" returns the number of items successfully scanned. Hence, checking for EOF is not the way to go.

    If you have a variable quantity of data from the file you're reading, perhaps you'd have better luck taking in each line at a time using "fgets()", checking for EOF, and (if the read is valid), extracting the data with "sscanf()".

  6. #6
    Registered User
    Join Date
    Mar 2012
    Posts
    61
    My teacher says that he will test our program with a text file. He never said how many items there would be in there, he only said it would be different for everyone.

    I can't use any functions we haven't gone over in class, so i can't use "sscanf()".

  7. #7
    Registered User
    Join Date
    Jun 2011
    Posts
    2,292
    We're not in your class, so we don't know which functions you're limited to, and that sort of hinders the help we can give.
    It seems that, so far, anduril462 has given you the best advice. That was three hours ago. Have you tried it yet?

  8. #8
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,467
    I assume your teacher means a different number of lines in the file, but each line will contain a first name, last name and number. That means, every time you call fscanf, you ask for one "line" or one "record" of information, which consists of 3 things. Thus, every call to fscanf asks for 3 items (and returns 3 if successful). The check for values other than 3 is in case the file is damaged and you have a line like
    Code:
    Jon Doe 123
    Fred Flintsto
    Then, the first fscanf call will return 3 because you have a complete record. The second time it will return 2 because you have an incomplete record. If you test for != EOF, your program will treat the second line as a successful read of a complete record, but the last name is truncated and there is no number, so the number field in your record will be garbage. That is why you check whether fscanf returns 3 instead of EOF.

  9. #9
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    21,650
    Quote Originally Posted by november1992
    My teacher says that he will test our program with a text file. He never said how many items there would be in there, he only said it would be different for everyone.
    What this means is that the number of members will be different. However, for each member, you know that there will be a first name, a last name and a number*. Therefore, you know that you should be comparing with 3, since there are 3 items read by fscanf.

    * Actually, I am just guessing what fn and ln mean. You might as well write first_name if fn means "first name". Also, what is the number for? If it is "age", then write age, not numb, and write a comment stating if it is number of years, months, days, etc.
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  10. #10
    Been here, done that.
    Join Date
    May 2003
    Posts
    1,157
    The thing nobody said, and the thing that seems to be bothering you, is

    By testing for 3 you make sure fscanf() read the proper number of values.
    But if you're at the end of the file, how many values will fscanf() read? 0.
    Therefore testing for 3 will work fine at the end of the file.
    Definition: Politics -- Latin, from
    poly meaning many and
    tics meaning blood sucking parasites
    -- Tom Smothers

  11. #11
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,467
    Quote Originally Posted by WaltP View Post
    By testing for 3 you make sure fscanf() read the proper number of values.
    But if you're at the end of the file, how many values will fscanf() read? 0.
    Therefore testing for 3 will work fine at the end of the file.
    This may be misleading. If you are exactly at the end of the file, it's true that fscanf will read 0 values, since there is no more input left in the file. This does not mean, however, that fscanf will return 0. Checking for 0 will fail if you are at the very end of the file. In fact, the standard says it will explicitly return EOF in that case, or for any input failure:
    Quote Originally Posted by C99 7.19.6.2p16
    The fscanf function returns the value of the macro EOF if an input failure occurs
    before the first conversion (if any) has completed. Otherwise, the function returns the
    number of input items assigned, which can be fewer than provided for, or even zero, in
    the event of an early matching failure.
    If there is a little garbage data after the last complete record you scanned, then the EOF test will fail. Depending on what you try to scan, and what the garbage data is, fscanf may return 0 (garbage doesn't match the format specifier), or may return something between 1 and N-1, where N is the number of format specifiers you are scanning for.

    The only assured way to handle any possible issue with scanf is to check for whether or not you read everything you asked for.
    Last edited by anduril462; 09-11-2012 at 11:40 PM. Reason: fix sentence order

  12. #12
    Been here, done that.
    Join Date
    May 2003
    Posts
    1,157
    Quote Originally Posted by anduril462 View Post
    This may be misleading. If you are exactly at the end of the file, it's true that fscanf will read 0 values, since there is no more input left in the file. This does not mean, however, that fscanf will return 0. Checking for 0 will fail if you are at the very end of the file.
    I never said check for 0. Reread my post or what you quoted! I said
    Quote Originally Posted by me
    Therefore testing for 3 [note: THREE, not ZERO] will work fine at the end of the file.
    Definition: Politics -- Latin, from
    poly meaning many and
    tics meaning blood sucking parasites
    -- Tom Smothers

  13. #13
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,467
    Quote Originally Posted by WaltP View Post
    I never said check for 0. Reread my post or what you quoted! I said
    Perhaps my reply wasn't as clear as it could have been either. Some of the bold parts were for november1992's sake as well, to reiterate what s/he wasn't getting. I know you never said check for 0, but I thought the following line could be interpreted as fscanf will return 0 on failure. I probably should have quoted it alone.
    Quote Originally Posted by WaltP View Post
    But if you're at the end of the file, how many values will fscanf() read? 0.
    That's the statement I had an issue with. I wanted to clarify for your sake if you didn't know, and for november1992's sake, that fscanf will read 0 elements, but it wont return 0 (it will return EOF) in that case. However, there are cases where fscanf will read 0 elements and return 0 as well.

  14. #14
    Been here, done that.
    Join Date
    May 2003
    Posts
    1,157
    Much clearer. Yes, I can see where my statement could be misconstrued. But no matter what it returns, it won't return 3 so the test will work.
    Definition: Politics -- Latin, from
    poly meaning many and
    tics meaning blood sucking parasites
    -- Tom Smothers

  15. #15
    Registered User
    Join Date
    Mar 2012
    Posts
    61
    I asked my TA whether to use 3 or EOF and he just told me to use EOF. But I'll just use 3 because it makes more sense to.

    So here is my code so far. At the fscanf part it reads the contents of the file but it also includes some random stuff.
    My TA said it's because I'm putting it directly into the struct. He said I should use a temporary variable to hold the names and numbers and then use strcpy to switch it to the structure. But how would that get rid of the random stuff at the end?

    http://i.imgur.com/6OLkD.png



    Code:
    #include <stdio.h>
     #include <stdlib.h>
     #include <string.h>
    
     
     #define MAXSIZE 256
     
     
     
     
    struct member_node{
        char firstname[MAXSIZE];
        char lastname[MAXSIZE];
        long long number;
        struct member_node *next;
    };
     
     void main(void){
     
     FILE *infile = NULL;
     FILE *outfile = NULL;
     char infilename[MAXSIZE];
     
     struct member_node *current;
     struct member_node *head;
    
     
     head = (struct member_node *)malloc(sizeof(struct member_node));
     current = head;
     
     while(infile == NULL){
        printf("Input file name:");
        scanf("%s",infilename);
        if((infile = fopen(infilename, "r")) == NULL) {
            printf("ERROR: file %s can not be opened!\n",infilename);
    
     }
     }
     
     
     printf("%s was opened\n",infilename);
     
     while(fscanf(infile,"%s %s %lld",current->firstname,current->lastname,&(current->number)) == 3)
     {
        current->next = (struct member_node *)malloc(sizeof(struct member_node));
        current->next->next = NULL;
        current = current->next;
        
        }
        
        
    
    for(current = head;current!= NULL;current=current->next){
        printf("\n%s %s %lld\n",current->firstname,current->lastname,(current->number));
        
        }

Page 1 of 2 12 LastLast
Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Read from file 'fscanf()'
    By leocfox in forum C Programming
    Replies: 5
    Last Post: 04-29-2012, 09:13 PM
  2. Using fscanf to read a file over and over again
    By juice_box in forum C Programming
    Replies: 1
    Last Post: 12-08-2010, 02:08 PM
  3. fscanf: read word from file
    By Dedalus in forum C Programming
    Replies: 1
    Last Post: 06-24-2009, 02:56 AM
  4. using FSCANF to read mixed text/double files
    By cfdprogrammer in forum C Programming
    Replies: 3
    Last Post: 03-23-2009, 03:18 AM
  5. read mix file: fscanf fgets
    By cfdprogrammer in forum C Programming
    Replies: 1
    Last Post: 03-20-2009, 11:38 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21