How to read a txt file into an array

This is a discussion on How to read a txt file into an array within the C Programming forums, part of the General Programming Boards category; Please I need help in knowing how to read a txt file into an array in C programming. example: ID ...

  1. #1
    Banned
    Join Date
    Aug 2009
    Posts
    30

    Unhappy How to read a txt file into an array

    Please I need help in knowing how to read a txt file into an array in C programming. example:

    ID Item_name Price
    1 MP3_player 19.99
    2 Mobile_Phone 25.99
    3 Digital_Organizer 29.99
    4 Pocket Pc 34.99
    5 Mp4_player 40.00
    6 Portable_media_player 49.99
    7 LCD_monitor 99.99
    8 Smartphone 299.99
    9 Laptop 399.99
    10 Tablet_Pc 499.99
    Last edited by Hitsugaya_KK; 08-18-2009 at 05:23 PM.

  2. #2
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    Breaking this down, what do you have a problem with:

    1) reading a file
    2) using an array
    3) using an array of strings
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  3. #3
    Banned
    Join Date
    Aug 2009
    Posts
    30
    I have a problem in reading a txt file while sorting the things in the txt file into fields: ID, Item_name Price.

  4. #4
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    Quote Originally Posted by Hitsugaya_KK View Post
    I have a problem in reading a txt file while sorting the things in the txt file into fields: ID, Item_name Price.
    Sounds like you should use a struct:
    Code:
    struct item {
          int ID;
          char name[64];
          int price;
    };
    Write a function that reads a single line from the file and returns a struct or struct pointer containing the struct for that item; you can add this struct (or a pointer to it) to an array. The prototype might be:
    Code:
    struct item *addItem (FILE *fh);
    Can you/are you allowed to use malloc()?
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  5. #5
    Banned
    Join Date
    Aug 2009
    Posts
    30
    yeah, I am allowed to use malloc

  6. #6
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    It's time to show your code on this. Even if it's incomplete, post it up. We won't do it for you.

    There are numerous examples of this on the board, you can search through the forum, for them, if you need examples to work from. Again, we're not going to do the searching or posting, or just code it up, for you.

    People learn best by doing. That was true 2,000 years ago, and it's still true today.

    So show your work, and make your questions specific. We don't know how to answer comments like "I don't know". If you don't know what to ask, we don't know what to answer.

    If you really have no idea what to ask, then study up with the tutorials in our forum, and on the web, as well. There are lots of good one's. If you get stuck on something, pop back in here, and ask away.

  7. #7
    Banned
    Join Date
    Aug 2009
    Posts
    30
    Code:
    #include <stdio.h>
    #include <iostream>
    #include <fstream> 
    
    
    
    
    int main()
    
    
    
    FILE *input_file;
    fp=fopen("c:\\shopping list.txt", "r");
    if(file==NULL) {
        printf("Error: can't open file.\n");    
        return 1;
    }
      else {
        printf("File opened successfully.\n");
    	    
    struct item {
          int ID;
          char name[64];
          int price;
    	  struct item *addItem (FILE *input_file);
    };
    
    printf( "1 - view the complete list of goods in the shop, with their prices" );
    printf( "2 – list the cheapest item on offer" );
    printf( "3 – “discount” option" );
    printf( "4 – choose items for purchase" );
    printf( "5 – total price for items" );
    printf( "6 - Exit");
    
    
    
    	
    	
    
        switch ( option ) {
    		case 1:           
    
            case 2:          
                
                break;
            case 3:         
      
            case 4:        
                printf( "choose item for purchase\n" );
    			
                break;
            case 5:            
                printf( "total price for items\n" );
                break;
    		case 6:
    			printf( "Exit\n" );
    
    
    
        }
        return 0;

  8. #8
    Banned
    Join Date
    Aug 2009
    Posts
    30
    As you can see the code isn't complete, I need to complete the first step in order to continue with other areas on my own :/. I guess I need some examples on this thread or somewhere else that could help me complete my program.
    Last edited by Hitsugaya_KK; 08-18-2009 at 06:33 PM.

  9. #9
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    Quote Originally Posted by Hitsugaya_KK View Post
    As you can see the code isn't complete, I need to complete the first step in order to continue with other areas on my own :/. I guess I need some examples on this thread or somewhere else that could help me complete my program.
    I would say the first step would be to process the file; the *last* would be to add the user interface/menu. So forget that stuff and write the program as if there were only one choice: to "view the complete list of goods in the shop". You don't even need the struct for now, you can just print each line out "Item X: " and then the line. The user interface cannot serve a purpose until it can be connected to working procedures, whereas those procedures can run on their own without an interface, so putting the menu in first is just clutter and distraction.

    By the way, the line in red here was intended to be a function prototype (look that up in your textbook in the chapter about functions) and not part of a struct:

    Code:
    struct item {
          int ID;
          char name[64];
          int price;
    	  struct item *addItem (FILE *input_file);
    };
    It is good you can use malloc(), I think you may need to.
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  10. #10
    Banned
    Join Date
    Aug 2009
    Posts
    30
    I found a website that I could get some ideas from which is Read file into array of structs - C example .

    Just wanted you to see this if this will help me better since I made little changes

    Code:
    #include <stdio.h>
    #include <iostream>
    #include <fstream> 
    #include <string.h>
    
    
    
    
    int main()
    	    
    struct item {
          int ID;
          char name[64];
          int price;
    
    
    	  struct item record [50]
    	   FILE *input_file;
    	   char stuff[121];
    	  
    	   char *goods;
            int reccount = 0;
            int k;
    
    
    		fp = fopen("C://shoppinglist.txt","r");
    if(file==NULL) {
        printf("Error: can't open file.\n");    
        return 1;
    }
      else {
        printf("File opened successfully.\n");
    
    		while (fgets(stuff,120,fp)) {
                    printf("%s",stuff);
    
                    item = strtok(stuff," ");
                    record[reccount].ID = atoi(goods);
    
                    item = strtok(NULL," ");
                    strcpy(record[reccount].name,goods);
    
                   item = strtok(NULL," ");
                    record[reccount].price = atoi(item)
    
                    }
    
            /* Close file */
    
            fclose(fp);
    
            /* Loop through and report on data */
    
            printf("Name Record\n");
            for (k=0; k<reccount; k++) {
                    printf("It is %s\n",record[k].name);
            
    
    printf( "1 - view the complete list of goods in the shop, with their prices" );
    printf( "2 – list the cheapest item on offer" );
    printf( "3 – “discount” option" );
    printf( "4 – choose items for purchase" );
    printf( "5 – total price for items" );
    printf( "6 - Exit");
    
    
    
    	
    	
    
        switch ( option ) {
    		case 1:           
    
            case 2:          
                
                break;
            case 3:         
      
            case 4:        
                printf( "choose item for purchase\n" );
    			
                break;
            case 5:            
                printf( "total price for items\n" );
                break;
    		case 6:
    			printf( "Exit\n" );
    
    
    
        }
        return 0;
    Last edited by Hitsugaya_KK; 08-18-2009 at 07:18 PM.

  11. #11
    Banned
    Join Date
    Aug 2009
    Posts
    30
    I managed to make my code similar to what I saw to in the link I recently provided. I would like someone to help me sort errors in the code .

  12. #12
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    Quote Originally Posted by Hitsugaya_KK View Post
    I managed to make my code similar to what I saw to in the link I recently provided. I would like someone to help me sort errors in the code .
    I hate to point this out but perhaps you have fallen a little behind in the work for this course? In your last post there is an unclosed curly brace, part of the struct, which will cause you a problem.

    The link you posted is fine or appears to be at first glance. One thing you will probably want to do is define the struct *outside* of main() since you will be using it in your other functions as well.

    To start with, simplify the struct to contain one element, the ID. This is the easiest thing to parse out of each line. The demo from the link does demonstrate a method, but you will need to transpose that method to make it work in the context of what you are trying to do. So apply that method in the function I mentioned earlier to extract the ID number from each line. When you can complete that successfully, you can add complications, one at a time, rather than trying to get everything right at once.
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  13. #13
    Banned
    Join Date
    Aug 2009
    Posts
    30
    ok then. So you are asking me to use something in relation to this? http://twiki.org/p/pub/Support/Locki...C-Examples.pdf . If so how do I apply it to this situation?

  14. #14
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    Quote Originally Posted by Hitsugaya_KK View Post
    ok then. So you are asking me to use something in relation to this? http://twiki.org/p/pub/Support/Locki...C-Examples.pdf . If so how do I apply it to this situation?
    Why do you want to apply it to the situation? And who is the "you" in that question?
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  15. #15
    Banned
    Join Date
    Aug 2009
    Posts
    30
    I had a feeling it was wrong. sorry MK27

    anyway, I have redone the code. So what do you think of this?

    Code:
    #include <stdio.h>
    #include <iostream>
    #include <fstream> 
    #include <string.h>
    
    
    struct item {
          int ID;
          char name[64];
          int price;
    
    int main(int argc, char *argv)
    FILE *fp;
    char retstr[BUFSIZ];
    char *f1, *f2, *f3, *p;
    int max_cnt=15;
    int i, cnt=0;
    
    
    
    
    	  struct item record [50]
    	  
    	 
    		fp = fopen("C://shoppinglist.txt","r");
    		if(file==NULL) {
        printf("Error: can't open file.\n");    
        return 1;
    }
      else {
        printf("File opened successfully.\n");
    	    
    
    		while (retstr, BUFSIZ, fp)!= NULL) {
    			{
    	if ((p = strchr(retstr, '\n')) != NULL)
    	*p = '\0';
    	if(cnt == max_cnt)
    	break;
    
    	f1=strtok(retstr, " ");
    	f2=strtok(NULL, " ");
    	f3=strtok(NULL, " ");
    	strcpy(usr[cnt].ID, f1);
    	strcpy(usr[cnt].name, f2);
    	strcpy(usr[cnt].price, f3);
    
    	cnt++;
    			}
    for(i=0; i < cnt; i++)
    printf("%d %s %d\n", record[i].ID, record[i].name,record[i].price);
    
    fclose(fp);
    exit(0);
    }
    printf( "1 - view the complete list of goods in the shop, with their prices" );
    printf( "2 – list the cheapest item on offer" );
    printf( "3 – “discount” option" );
    printf( "4 – choose items for purchase" );
    printf( "5 – total price for items" );
    printf( "6 - Exit");
    
    
    
    	
    	
    
        switch ( option ) {
    		case 1:           
    
            case 2:          
                
                break;
            case 3:         
      
            case 4:        
                printf( "choose item for purchase\n" );
    			
                break;
            case 5:            
                printf( "total price for items\n" );
                break;
    		case 6:
    			printf( "Exit\n" );
    
    
    
        }
        return 0;




    [

Page 1 of 4 1234 LastLast
Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Newbie homework help
    By fossage in forum C Programming
    Replies: 3
    Last Post: 04-30-2009, 05:27 PM
  2. opening empty file causes access violation
    By trevordunstan in forum C Programming
    Replies: 10
    Last Post: 10-22-2008, 12:19 AM
  3. Replies: 3
    Last Post: 03-04-2005, 02:46 PM
  4. simulate Grep command in Unix using C
    By laxmi in forum C Programming
    Replies: 6
    Last Post: 05-10-2002, 05:10 PM

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