Thread: reading a file

Hybrid View

Previous Post Previous Post   Next Post Next Post
  1. #1
    Registered User
    Join Date
    Sep 2006
    Posts
    104

    Question reading a file

    I'm trying to do Write a C program that displays a three option menu of: 1. Enter A Record, 2. Display List, 3. Terminate. Option 1 should ask for Last Name (character string up to 25 long), First Name (character string up to 25 long), Sex (enumerated data type of M/F), Grade (enumerated data type of A/B/C/D/F). The data should be placed in a structure and inserted into a linked list ordered by Last Name. Option 2 should list all records on the screen. Option 3 should write the linked list to a disk file and exit. When the program is invoked it should read the existing data in the disk file if it exists before displaying the menu. After options 1 and 2 are complete the menu should be displayed again.

    I'm having an issues etting up the file to be read. ANd ideas this is what i have gotten so far.

    Code:
     #include <stdio.h>
    #include <string.h>
    
    #define FLASE 0
    #define TRUE 1
    #define Nlen 25
    
    typedef struct person{
         char FName [Nlen +1];
         char LName [Nlen +1];
         char Sex;
         char Grade;
         struct person *Next;
    } PERSON;
    
    void PrintList (PERSON*);
    int DeletePerson;
    PERSON* InsertNode (PERSON*, PERSON*);     
    
    main ()
    {
        PERSON *STU; //TEmp pointer used to creat list
        char ANS;    //User responce
        int Len,      //Name Length
            Deleted; //True if requested item deleted
        char FName [Nlen +1];  // first name
        char LName [Nlen +1];  // lase name
        char Grade, Sex; 
        FILE *fin;
         fin = fopen( "data.dat", "rw");
         
    PERSON *TOP = NULL; //Initialize top list point to Null     
        
         
     while (fscan(fin, %-*s %-*s %c %c\n, Nlen, STU->LName, STU->FName, STU->Sex,STU->Grade) != EOF){
          
     
     getchar ();
     getchar ();
     return 0;
    }

  2. #2
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,005
    Code:
    while (fscan(fin, %-*s %-*s %c %c\n, Nlen, STU->LName, STU->FName, STU->Sex,STU->Grade) != EOF)
    Bad guess.

    Is your data supposed to be stored in the file as text? Or the binary of the struct? If text, use fgets/sscanf (and read up on *scanf -- again if necessary). If binary, use fread.
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

  3. #3
    Registered User
    Join Date
    Sep 2006
    Posts
    104
    I need to store it as text.
    Code:
    while (fscan(fin, '%-*s %-*s %c %c\n", Nlen, STU->LName, STU->FName,
    STU->Sex,STU->Grade) != EOF)
    dose this look right for know
    Code:
      #include <stdio.h>
    #include <string.h>
    
    #define FLASE 0
    #define TRUE 1
    #define Nlen 25
    
    typedef struct person{
         char FName [Nlen +1];
         char LName [Nlen +1];
         char Sex;
         char Grade;
         struct person *Next;
    } PERSON;
    
    void PrintList (PERSON*);
    int DeletePerson;
    PERSON* InsertNode (PERSON*, PERSON*);     
    
    main ()
    {
        PERSON *STU; //TEmp pointer used to creat list
        int Ans;    //User responce
        int Len,      //Name Length
            Deleted; //True if requested item deleted
        char FName [Nlen +1];  // first name
        char LName [Nlen +1];  // lase name
        char Grade, Sex; 
        FILE *fin;
         fin = fopen( "data.dat", "rw");
         
    PERSON *TOP = NULL; //Initialize top list point to Null     
        
         
     while (fscanf(fin, "%-*s %-*s %c %c\n", Nlen, STU->LName, STU->FName, STU->Sex,STU->Grade) != EOF){
          printf ("chose option you want to do\n");
          printf ("Option 1 : Enter New Recode");
          printf ("Option 2 : Display List");
          scanf ("%d", Ans);
          
           switch (Ans){
              case '1' :       
                 do {
                  STU = (PERSON*) malloc (sizeof(PERSON));
                  if (STU == NULL)
                    printf ("Error -- could not allocate memory\n\n");
                  else {
                     printf ("\nEnter students first name ( uo to %d letters):", Nlen);
                     fgets (STU->FName, Nlen+1, stdin);
                     Len = strlen (STU->FName);
                       if (STU->FName[Len-1]== '\n')
                           STU->FName [Len-1] == '\0';
                      
                      printf ("\nEnter students first name ( uo to %d letters):", Nlen);
                     fgets (STU->LName, Nlen+1, stdin);
                     Len = strlen (STU->LName);
                       if (STU->LName[Len-1]== '\n')
                           STU->LName [Len-1] = '\0';  
                       
                     printf ("Please enter Sex");
                     scanf ("%c", &STU->Sex);
                     printf ("Please enter Grade");
                     scanf ("%c", &STU->Grade);  
                     STU->Next= NULL;          
                   
     
     getchar ();
     getchar ();
     return 0;
    }

  4. #4
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,005
    Code:
    while (fscan(fin, '%-*s %-*s %c %c\n", Nlen, STU->LName, STU->FName,
    STU->Sex,STU->Grade) != EOF)
    The scanf family does not have these modifiers in the manner you think.

    Are you having trouble reading fgets/sscanf? It only makes life easier for you.
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

  5. #5
    Registered User
    Join Date
    Sep 2006
    Posts
    104
    so what your saying is that i do not need -* in there just teh s to say that it is a string

    but know im getting this error message 44 H:\My Documents\Untitled1.cpp `malloc' undeclared (first use this function) on thsi line what dose it mean.

    Code:
    STU = (PERSON*) malloc (sizeof(PERSON));

  6. #6
    Registered User
    Join Date
    Sep 2006
    Posts
    35
    Quote Originally Posted by redmondtab
    but know im getting this error message 44 H:\My Documents\Untitled1.cpp `malloc' undeclared (first use this function) on thsi line what dose it mean.
    If I'm not mistaken, the compiler cannot locate the prototype for malloc, so you must add this somewhere in your code:
    Code:
    #include <stdlib.h>

  7. #7
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,005
    Quote Originally Posted by redmondtab
    so what your saying is that i do not need -* in there just teh s to say that it is a string
    Yes and no. You really want to limit the width of the string input, but you can't do it that way. For now a short version is to hard-code it, like this: %25[^ ].
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

  8. #8
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,612
    The fprintf() function prints to a file.

  9. #9
    Registered User
    Join Date
    Sep 2006
    Posts
    104
    i want to print whats in the file to the screen. Did i not read it in.

  10. #10
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,612
    Quote Originally Posted by redmondtab
    i want to print whats in the file to the screen. Did i not read it in.
    Actually no you did not, if answer is ever equal to two before it equals one. The switch-case would jump to that case and try to print a bunch of presumably empty values. Please check your logic.

    And it won't even appear on the screen since you called printf incorrectly, winning you a compile-time error.

  11. #11
    Registered User
    Join Date
    Sep 2006
    Posts
    104
    so if i write it like this will it pull it from the file and print the data to the screen, becuase that is what i want to do. IF there is data in the file priint the list. IF there is no data. Then as the user to input the data. or is there a bette way to write that statment. BEcasue i know i still need to put it into a loop with an option to teremat. But i wanted to do it in small steps so that i could walk though what i was doing and get the code correct as i went.

    Code:
    printf (fin, "%s %s %c %c\n",  LName, FName, Sex,Grade);

  12. #12
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,005
    Code:
    while (fscanf(fin, "%25[^ ]. %25[^ ].%c %c\n", Nlen, STU->LName, STU->FName, STU->Sex,STU->Grade) != EOF){
    Are there really periods [nod to those elsewhere: full stops] in the text?
    And don't compare for one possible failure before assuming you got what you wanted, check for success -- that is, did you successfully scan the 5 items?
    And why not use fgets/sscanf?
    And since it's whitespace, I guess I could have used %25s instead of %25[^ ]. (The period at is at the end of the sentence to mark the end of the sentence, not part of the format specifier.)
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

  13. #13
    Registered User
    Join Date
    Sep 2006
    Posts
    104

    Question

    I'm able to get it into the while statment and it shows the options. But i keep gettign a referance window in dos when i hit one of the options what did i do wrong.


    Code:
     #include <stdio.h>
    #include <string.h>
    #include <stdlib.h>
    
    
    #define FLASE 0
    #define TRUE 1
    #define Nlen 25
    
    typedef struct person{
         char FName [Nlen +1];
         char LName [Nlen +1];
         char Sex;
         char Grade;
         struct person *Next;
    } PERSON;
    
    void PrintList (PERSON*);
    int DeletePerson;
    PERSON* InsertNode (PERSON*, PERSON*);     
    
    main ()
    {
        PERSON *STU; //TEmp pointer used to creat list
        int Ans;    //User responce
        int Len,      //Name Length
            Deleted; //True if requested item deleted
        char FName [Nlen +1];  // first name
        char LName [Nlen +1];  // lase name
        char Grade, Sex, Ans1; 
        FILE *fin;
        
         
    PERSON *TOP = NULL; //Initialize top list point to Null     
     fin = fopen( "e:data.txt", "rw");    
         
     while (fscanf(fin, "%25s %25s %c %c\n", Nlen, STU->LName, STU->FName, STU->Sex,STU->Grade) == EOF){
     {
          
          printf ("chose option you want to do\n");
          printf ("Option 1 : Enter New Recode\n");
          printf ("Option 2 : Display List\n");
          printf ("Option 3 : Quit\n");
          scanf ("%d", Ans);
          
           switch(Ans){
              case '1' :       
                STU = (PERSON*) malloc (sizeof (PERSON));
                 if (STU == NULL)
                    printf ("Error -- could not allocate memory\n\n");
                 else {
                     printf ("\nEnter students first name ( uo to %d letters):", Nlen);
                     fgets (STU->FName, Nlen+1, stdin);
                     Len = strlen (STU->FName);
                       if (STU->FName[Len-1]== '\n')
                           STU->FName [Len-1] == '\0';
                      
                      printf ("\nEnter students first name ( uo to %d letters):", Nlen);
                     fgets (STU->LName, Nlen+1, stdin);
                     Len = strlen (STU->LName);
                       if (STU->LName[Len-1]== '\n')
                           STU->LName [Len-1] = '\0';  
                       
                     printf ("Please enter Sex");
                     scanf ("%c", &STU->Sex);
                     printf ("Please enter Grade");
                     scanf ("%c", &STU->Grade);  
                     STU->Next= NULL; 
                      break;         
                    } //else statment end
                             
                 
                case '2' :
                     fscanf(fin, "%25s %25s %c %c\n", Nlen, STU->LName, STU->FName, &STU->Sex, &STU->Grade);
                     printf ("%s %s %c %c\n", LName, FName, Sex, Grade);
                     break; 
                            
                  case '3' :  
                      printf ("you chose to exit.  Hit enter to close");  
                      break; 
                }//end of switch
          } // end of while
          }
     getchar ();
     getchar ();
     return 0;
    }
    Last edited by redmondtab; 10-05-2006 at 05:53 PM.

  14. #14
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,612
    I hope no one minds this, but I've been making some attempts. Maybe something like this is closer to what the OP wants:
    Code:
    #include <assert.h>
    #include <stdio.h>
    #include <stdlib.h>
    
    #define Nlen    26
    
    typedef struct person_t {
       char FName[Nlen];
       char LName[Nlen];
       char Sex;
       char Grade;
       struct person_t *next;
    } PERSON;
    
    void amend_file( char file[], PERSON *STU );
    void show_file( char file[], PERSON *STU );
    
    int main ( void )
    {
       PERSON *STU;
       int Ans;
       char file[] = "data.txt";
    
       do
       {
          printf("1. Enter new record\n"
                 "2. Display List\n"
                 "3. Quit\n\n");
          printf("Prompt: ");
          fflush(stdout);
          if ( scanf("%d", &Ans) == 1 ) /* get answer */
          {
             STU = malloc(sizeof *STU);
             if (STU == NULL)
             {
                perror("PERSON");
                exit(EXIT_FAILURE);
             }
             switch(Ans)
             {
                case 1:
                   amend_file(file, STU);
                   break;
                case 2:
                   show_file(file, STU);
                   break;
                case 3: default:
                   Ans = 3;
                   break;
             }
          } /* /get answer */
       }
       while ( Ans != 3 );
       free(STU);
       return EXIT_SUCCESS;
    }
    /*
     * amend_file: Enter stuff into the working file.
     * Very much a bare bones function so far; work on making this better
     * Perhaps make it work with a linked list, as your struct suggests?
     */
    void amend_file( char file[], PERSON *HEAD )
    {
       assert(HEAD != NULL);
       FILE *fin = fopen(file, "a");
       if ( fin == NULL )
       {
          perror(file);
          exit(EXIT_FAILURE);
       }
       printf("Enter new record (EOF to quit): ");
       while (
        scanf("%s %s %c %c", HEAD->FName, HEAD->LName, &HEAD->Sex,
          &HEAD->Grade) == 4
       )
       {
         fprintf(fin, "%s %s %c %c\n", HEAD->FName, HEAD->LName, HEAD->Sex,
            HEAD->Grade);
         fflush(fin);
       }
       fclose(fin);
    }
    /*
     * show_file: Reads the working file.
     * Bare bones again...
     */
    void show_file ( char file[], PERSON *HEAD )
    {
      assert(HEAD != NULL);
      int i = 1;
      FILE *fout = fopen(file, "r");
      if (file == NULL)
      {
        perror(file);
        exit(EXIT_FAILURE);
      }
      while (
       fscanf(fout, "%s %s %c %c", HEAD->FName, HEAD->LName, &HEAD->Sex,
         &HEAD->Grade) == 4
      )
      {
        printf("Record %d: %s %s %c %c\n", i, HEAD->FName, HEAD->LName,
           HEAD->Sex, HEAD->Grade);
        i++;
      }
      fclose(fout);
    }
    I was able to make this text file.
    $ ./a
    1. Enter new record
    2. Display List
    3. Quit

    Prompt: 1
    Enter new record (EOF to quit): Tom Capobres M B
    George Carlin M A
    Frank Sinatra M C
    Matt Outlaw M A
    Betsy Storrs F B
    1. Enter new record
    2. Display List
    3. Quit

    Prompt: 2
    Record 1: Tom Capobres M B
    Record 2: George Carlin M A
    Record 3: Frank Sinatra M C
    Record 4: Matt Outlaw M A
    Record 5: Betsy Storrs F B
    1. Enter new record
    2. Display List
    3. Quit

    Prompt: 3

    Sorry it's just so ugly though...

  15. #15
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,612
    > BEcasue i know i still need to put it into a loop with an option to teremat
    As you read parts of the file I would believe that is a loop with a requirement to terminate eventually.

    >IF there is data in the file priint the list. IF there is no data. Then as the user to input the data.
    -Read data from the file first.
    -If that fails, ask the user if there is more data
    -If yes, get input from the user and store it somewhere. If no, exit.
    -Print that to the file using something like fprintf()
    -loop

    Code:
    scanf("%d", &Ans);
    The first argument to printf is and always was a format string, not a FILE *
    Code:
    printf ("%s %s %c %c\n",  LName, FName, Sex,Grade);

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. opening empty file causes access violation
    By trevordunstan in forum C Programming
    Replies: 10
    Last Post: 10-21-2008, 11:19 PM
  2. Formatting the contents of a text file
    By dagorsul in forum C++ Programming
    Replies: 2
    Last Post: 04-29-2008, 12:36 PM
  3. Replies: 3
    Last Post: 03-04-2005, 02:46 PM
  4. Possible circular definition with singleton objects
    By techrolla in forum C++ Programming
    Replies: 3
    Last Post: 12-26-2004, 10:46 AM
  5. System
    By drdroid in forum C++ Programming
    Replies: 3
    Last Post: 06-28-2002, 10:12 PM