fgets/sscanf

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Tango Charlie
    New Member
    • Mar 2007
    • 3

    fgets/sscanf

    I'm trying to get this program to open and read a *.txt file and save in an array in traditional C. CLASS is defined as "filename.t xt" in the header file. It reads from the file, I think, but it is nothing but garbage. Please offer suggestions...

    Code:
    #include "cl_info.h"
    
    void get_class_data(struct student class[])
    {
       char   last_name[MAXWORD];
       char   line[MAXLINE];
       int    cnt;
       int    i = 0;
       int    n;
       FILE   *ifp;
    
       ifp = fopen(CLASS, "r");
       if (ifp == NULL) {
          printf("\nCannot open %s - Goodbye!\n\n", CLASS);
          exit(1);
       }
       for (i = 0; fgets(line, MAXLINE, ifp) != NULL; ++i){
    	   cnt = sscanf_s(line, "%s%d %c",
    		   last_name, &class[i].student_id, &class[i].grade);
    	   assert(cnt == 3);
    	   n = strlen(last_name);
    	   class[i].last_name = calloc(n + 1, sizeof(char));
    	   assert(class[i].last_name != NULL);
    	   strcpy(class[i].last_name, last_name);
       }
       if (i != CLASS_SIZE) {
          printf("\n%s\n\n",
             "ERROR: Unexpected class size in %s - Goodbye!\n\n", CLASS);
          exit(1);
       }
    }
    I can't wait to understand this language!
  • RedSon
    Recognized Expert Expert
    • Jan 2007
    • 4980

    #2
    Questions about reading and parsing text files in C has been asked and answered hundreds of times. What resources have you been able to find on this web site and by searching google, and google groups?

    Comment

    Working...