Thread: reading a file

  1. #31
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,612
    > would you like me to post my linked list and sort alagrithem them and the work on puting the two together.
    If you have a problem doing that yourself.

    > the other problem that i have is that 1 i can get out of the loop.
    Type EOF (ctrl+z on windows) to break the loop, just as the prompt said.

    > I should be able to enter in one data and the be prompted at the list again.
    > How do I do that.
    Basically, turn the while loop found in amend() into an if statement. Be advised I never typed that program with the intention of you using it. Other people have made fine suggestions, such as using fgets() and sscanf() to read user input. I'm only trying to help you visualize your program so that you can appreciate the steps that need to be taken. What I posted was bare-bones, if that.

    > here is what i came up for my linked list.
    Linked lists with ints in them are largely for instruction purposes AFAIK. In real world programs the nodes can be much more than just that. The struct you came up with before is also a node:
    Code:
    typedef struct person_t {
       char FName[Nlen];
       char LName[Nlen];
       char Sex;
       char Grade;
       struct person_t *next;
    } PERSON;
    What you need to do is develop functions that do what you need with the node type. Like sort(), push(), pop() ... whatever you need.

    > just courise how do i pass the rest of the struct so that it all prints together.
    After you've built a list, pass the head node to the printing function. Have the print function walk through the list and output everything.

    > So I should do the sort first then pass it to the linked list or the other way around
    Build the list from your input and then sort the list, ideally.

    Do not attempt to write the entire program in one sitting. Address one need at a time, and make sure that whatever you write actually works before you move on to something else.
    Last edited by whiteflags; 10-06-2006 at 02:30 PM.

  2. #32
    Registered User
    Join Date
    Sep 2006
    Posts
    104
    i think this program i have been writing just kind of lost with it. i can't get it to go into the while loop. But i think i should not use a while statment there and that is causing me not to go into my loop. its nota s neat as yours but i can undertand what im doing in it.
    error
    92 E:\888.cpp cannot convert `FILE*' to `const char*' for argument `1' to `void perror(const char*)'
    121 E:\888.cpp expected `while' at end of input
    121 E:\888.cpp expected `(' at end of input
    121 E:\888.cpp expected primary-expression at end of input
    121 E:\888.cpp expected `;' at end of input
    121 E:\888.cpp expected `}' at end of input

    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, i,      //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");    
         
     do
     {
      fscanf(fin, "%25s %25s %c %c\n", STU->LName, STU->FName, &STU->Sex, &STU->Grade);   
          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");
           fflush(stdout);
          scanf ("%d", Ans);
           if ( scanf("%d", &Ans) == 1 ) /* get answer */
          {
             STU = (PERSON*) malloc (sizeof (PERSON));
             if (STU == NULL)
             {
                perror("PERSON");
                exit(EXIT_FAILURE);
             }
           switch(Ans){
              case '1' :       
                     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);  
                    
           
           
           while (scanf("%s %s %c %c", STU->FName, STU->LName, &STU->Sex,
          &STU->Grade) == 4)
        {
         fprintf(fin, "%s %s %c %c\n", STU->FName, STU->LName, STU->Sex,STU->Grade);
         fflush(fin);
       }
       fclose(fin);
    break;         
    
                             
                 
                case '2' :
       i = 1;
       fin = fopen( "e:data.txt", "r");
        if (fin == NULL)
      {
        perror(fin);
        exit(EXIT_FAILURE);
      }
      while (fscanf(fin, "%s %s %c %c", STU->FName, STU->LName, &STU->Sex,
         &STU->Grade) == 4)
      {
        printf("Record %d: %s %s %c %c\n", i, STU->FName, STU->LName,
           STU->Sex, STU->Grade);
        i++;
      }
      fclose(fin);
            break;                 
                  
                  case '3' :  
                      printf ("you chose to exit.  Hit enter to close");  
                      break; 
                  }//end of switch
          }  while ( Ans != 3 );
          printf("1. Enter new record\n"
                 "2. Display List\n"
                 "3. Quit\n\n");
          printf("Prompt: ");
          fflush(stdout);
          free(STU);
          
    
     getchar ();
     getchar ();
     return 0;
    }
    Last edited by redmondtab; 10-06-2006 at 03:13 PM.

  3. #33
    Registered User
    Join Date
    Oct 2001
    Posts
    2,934
    > perror(fin);
    perror takes a string as an argument, not a FILE *. So you could change it to:
    Code:
        perror( "e:data.txt" )
    > if ( scanf("%d", &Ans) == 1 ) /* get answer */
    > {
    It doesn't appear you ever closed this if statement with a corresponding right brace.

  4. #34
    Registered User
    Join Date
    Sep 2006
    Posts
    104

    Question

    ok i change it and i still ge this error message i get this every time i try to run the program help please am i getting this error because i trying to us my usb drive for two things ar once.


    888.exe application error

    The instrucation at "0x77c44995 referance meoary at "0x7c80b643. teh memory could not be "written'


    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, i,      //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");    
         
     do
     {
      fscanf(fin, "%25s %25s %c %c\n", STU->LName, STU->FName, &STU->Sex, &STU->Grade);   
          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");
           fflush(stdout);
          scanf ("%d", Ans);
           if ( scanf("%d", &Ans) == 1 ) /* get answer */
             STU = (PERSON*) malloc (sizeof (PERSON));
             if (STU == NULL)
             {
                perror("PERSON");
                exit(EXIT_FAILURE);
             }
           switch(Ans){
              case '1' :       
                     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);  
                    
           
           
           while (scanf("%s %s %c %c", STU->FName, STU->LName, &STU->Sex,
          &STU->Grade) == 4)
        {
         fprintf(fin, "%s %s %c %c\n", STU->FName, STU->LName, STU->Sex,STU->Grade);
         fflush(fin);
       }
       fclose(fin);
    break;         
    
                             
                 
                case '2' :
       i = 1;
       fin = fopen( "e:data.txt", "r");
        if (fin == NULL)
      {
        perror("e:data.txt");
        exit(EXIT_FAILURE);
      }
      while (fscanf(fin, "%s %s %c %c", STU->FName, STU->LName, &STU->Sex,
         &STU->Grade) == 4)
      {
        printf("Record %d: %s %s %c %c\n", i, STU->FName, STU->LName,
           STU->Sex, STU->Grade);
        i++;
      }
      fclose(fin);
            break;                 
                  
                  case '3' :  
                      printf ("you chose to exit.  Hit enter to close");  
                      break; 
                  }//end of switch
          }  while ( Ans != 3 );
          printf("1. Enter new record\n"
                 "2. Display List\n"
                 "3. Quit\n\n");
          printf("Prompt: ");
          fflush(stdout);
          free(STU);
    
     getchar ();
     getchar ();
     return 0;
    }
    Last edited by redmondtab; 10-06-2006 at 04:41 PM.

  5. #35
    Registered User
    Join Date
    Oct 2001
    Posts
    2,934
    > scanf ("%d", Ans);
    You're missing an & here:
    Code:
          scanf ("%d", &Ans);
    > STU = (PERSON*) malloc (sizeof (PERSON));
    You don't need to cast the result of malloc. Unless you're compiling in C++ mode.
    Code:
             STU = malloc (sizeof (PERSON));

  6. #36
    Registered User
    Join Date
    Oct 2001
    Posts
    2,934
    > scanf ("%d", Ans);
    I just noticed you already have a scanf just below this one. You can remove this one.

  7. #37
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,005
    From my perspective, I'd say that it might be good to back up and get a handle on reading data from a file before adding more stuff. For something simple, maybe like this.
    Code:
    #include <stdio.h>
    #include <string.h>
    
    struct person
    {
        char FName [26];
        char LName [26];
        char Sex;
        char Grade;
        struct person *Next;
    };
    
    void person_print(const struct person *student, FILE *stream)
    {
        fprintf(stream, "%-25s %-25s %c %c\n",
                student->LName, student->FName, student->Sex, student->Grade);
    }
    
    int main ()
    {
        static const char filename[] = "data.dat";
        FILE *file = fopen(filename, "r");
        if ( file != NULL )
        {
            struct person student;
            char line[sizeof student];
            while ( fgets(line, sizeof line, file) != NULL )
            {
                if ( sscanf(line, "%25s %25s %c %c",
                            student.LName, student.FName,
                            &student.Sex, &student.Grade) == 4 )
                {
                    person_print(&student, stdout);
                }
            }
            fclose(file);
        }
        else
        {
            perror(filename);
        }
        return 0;
    }
    This just prints the contents of the file to the stdout (for now, later on you may want to also print to a file).

    I also recommend using fgets/sscanf for the menu. With a "large enough" input buffer, this relieves you of issues of cleaning up the stdin.
    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. #38
    Registered User
    Join Date
    Sep 2006
    Posts
    104

    Unhappy

    ok know it will read the fil. I'm know having issues. saving it to a linked list with arrays . i pulled the example online. So I know that im missing items. Help please. Or should i do the sort first. I have tried to pt it into a linked list but get errorrs. Sorry if i ask too many question Still learning. have a long way to go....

    118 E:\Untittest2.cpp `record' does not name a type
    125 E:\Untittest2.cpp `Entry' does not name a type
    128 E:\Untittest2.cpp redefinition of `int listHead'
    124 E:\Untittest2.cpp `int listHead' previously declared here
    129 E:\Untittest2.cpp expected constructor, destructor, or type conversion before '=' token
    129 E:\Untittest2.cpp expected `,' or `;' before '=' token
    130 E:\Untittest2.cpp expected unqualified-id before "while"
    130 E:\Untittest2.cpp expected `,' or `;' before "while"


    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[] = "e:data.txt";
        int Records [1000];
        
        
      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 = (PERSON*) malloc (sizeof (PERSON));
             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 );
        printf("1. Enter new record\n"
                 "2. Display List\n"
                 "3. Quit\n\n");
          printf("Prompt: ");
          fflush(stdout);
       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): ");
       printf ("\nEnter students first name ( up to %d letters):", Nlen);
       printf ("\nEnter students last name  ( up to %d letters):", Nlen);
        printf ("\nPlease enter Sex");
        printf ("\nPlease enter Grade\n");
       scanf("%s %s %c %c", HEAD->FName, HEAD->LName, &HEAD->Sex,
          &HEAD->Grade);
       
       
         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 b = 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", b, HEAD->FName, HEAD->LName,
           HEAD->Sex, HEAD->Grade);
        b++;
      }
      fclose(fout);
    }
    
    
    void record Entry {
        integer next; // index of next entry in array
        integer prev; // previous entry (if double-linked)
        string name;
        real balance;
    }
    int listHead;
     int Entry Records[1000];
    
      int i;
       int listHead;
      i = listHead;
          while i >= 0 { '// loop through the list
         printf i, Records[i].LName, Records[i].FName, Records[i].sex, Records[i].Sex; // print entry
         i = Records[i].next;
          }

  9. #39
    Registered User
    Join Date
    Sep 2006
    Posts
    104

    Question

    ok Im still lost. Im trying to use a sort linked list any ideas of why it is not working
    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[] = "e:data.txt";
        int Records [1000];
        
        
      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 = (PERSON*) malloc (sizeof (PERSON));
             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 );
        printf("1. Enter new record\n"
                 "2. Display List\n"
                 "3. Quit\n\n");
          printf("Prompt: ");
          fflush(stdout);
       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): ");
       printf ("\nEnter students first name ( up to %d letters):", Nlen);
       printf ("\nEnter students last name  ( up to %d letters):", Nlen);
        printf ("\nPlease enter Sex");
        printf ("\nPlease enter Grade\n");
       scanf("%s %s %c %c", HEAD->FName, HEAD->LName, &HEAD->Sex,
          &HEAD->Grade);
       
       
         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 b = 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", b, HEAD->FName, HEAD->LName,
           HEAD->Sex, HEAD->Grade);
        b++;
      }
      fclose(fout);
    }
    
    
    void record Entry {
        integer next; // index of next entry in array
        integer prev; // previous entry (if double-linked)
        string name;
        real balance;
    }
    int listHead;
    int Entry Records[1000];
    
      int i;
       int listHead;
      i = listHead;
          while i >= 0 { '// loop through the list
         printf i, Records[i].LName, Records[i].FName, Records[i].sex, Records[i].Sex; // print entry
         i = Records[i].next;
          }

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