Thread: Split a textfile in an array

  1. #1
    Registered User
    Join Date
    Sep 2010
    Posts
    17

    Split a textfile in an array

    Dear Programmers,

    i have a question about splitting a textfile into an array. I have an textfile month.text which look like this:

    "JAN","FEB","MAR","APR","MAY","JUN","JUL","AUG","O CT","NOV","DEC"

    Now, want i want is to read the file, split the "substrings" into an array, and put these name in alphabet order.

    So, what is did is:
    Code:
    FILE *fp = NULL; 
    fp = fopen("c:\\month.txt", "r");             //filename is month.txt, and the "r" for read
    char c;
    while((c = fgetc(input)) != EOF){
          if(c == ','){stop, and put it in an array, and make new array for the next month     }
         next character
    }
    How can i do this?

    Best Regards,

    Peter

  2. #2
    Registered User
    Join Date
    Oct 2008
    Location
    TX
    Posts
    2,059
    See the manpage of strtok().

  3. #3
    Registered User
    Join Date
    Sep 2010
    Posts
    17
    if i have something like:


    Code:
    	char *ptr;
    	char str[]="Testing,testing0,testing1,testing2,testing3,";
    	ptr = strtok(str, ",");
    i keeps the error 'strtok': identifier not found

    i have included

    Code:
    #include <stdio.h>
    #include <string.h>

  4. #4
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    strtok Scans s1 for the first token not contained in s2.

    Syntax:
    char *strtok(char *s1, const char *s2);

    Prototype in:
    string.h

    Remarks:
    strtok considers the string s1 to consist of a
    sequence of zero or more text tokens,
    separated by spans of one or more characters
    from the separator string s2.

    The first call to strtok returns a pointer to
    the first character of the first token in s1
    and writes a null character into s1
    immediately following the returned token.

    Subsequent calls with null for the first
    argument will work through the string s1 in
    this way, until no tokens remain.

    The separator string, s2, can be different
    from call to call.

    Return Value:
    strtok returns a pointer to the token found in
    s1. A null pointer is returned when there are
    no more tokens.

    Portability:
    strtok is available on UNIX systems and is
    defined in ANSI C.

    Example:
    Code:
     #include <string.h>
     #include <stdio.h>
    
     int main(void)
     {
        char input[16] = "abc,d";
        char *p;
    
        /* strtok places a NULL terminator
        in front of the token, if found */
        p = strtok(input, ",");
        if (p)   printf("%s\n", p);
    
        /* A second call to strtok using a NULL
        as the first parameter returns a pointer
        to the character following the token  */
        p = strtok(NULL, ",");
        if (p)   printf("%s\n", p);
        return 0;
     }

  5. #5
    Registered User
    Join Date
    Sep 2010
    Posts
    17
    but how to implement this with a textfile...

    now i have

    Code:
    #include "stdafx.h"
    #include <stdio.h>
    #include <string.h>
    
    
    
    int main (void){
    
    
    
    	FILE *fp = NULL;
    	fp = fopen("c:\\month.txt", "r");
    	
        
    	//check if we can access the file, if not, return 1
    	if( fp == NULL ){
    		printf ("cannot open file");
    		return 1;
    	}
                    //WRONG!!
    	char *p = NULL;
    	if(strtok(p, ",")){
    	}
    
    
    }

  6. #6
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    Use fgets(myCharArray, sizeof(myCharArray), filePointer), to put one line of text at a time, into your myCharArray, which should have room for 100 char's or so.

    Then you'll have strtok() work on each line, one line at a time. You can't use strtok() directly in a file, AFAIK.

    Your original logic COULD have been used for this, but it isn't as easy as using fgets() and strtok(). You'll get it, no problem, with some help.

  7. #7
    Registered User
    Join Date
    Sep 2010
    Posts
    17
    so, i need to put one line in an array, then use the strtok function to put the different substring in another array?

  8. #8
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    Quote Originally Posted by peterderijp View Post
    so, i need to put one line in an array, then use the strtok function to put the different substring in another array?
    Yes, that's the easy way. It seems muddled, but strtok() adds some end of char markers: '\0', to the string, as it's breaking out each token. That's not something you want to have happen in your text file, trust me.

    So
    Open the file for input
    while((fgets()...)!= NULL) { // puts each line of text, into your 1D char array
    strtok() breaks out each word from there, and puts it into your 2D array.

    Let me take a peek at your latest code...

    #include <stdafx.h> ?? This is C++, not C. Probably shouldn't be using both stdio.h and stdafx.h, together, but I'm not sure if they conflict or not. Why this file?

  9. #9
    Registered User
    Join Date
    Sep 2010
    Posts
    17
    that's because i use the Visual C++ compiler i though

  10. #10
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    Quote Originally Posted by peterderijp View Post
    that's because i use the Visual C++ compiler i though
    Your compiler has actually TWO compilers: 1 for C++ (which you are using now), and one for C (which you should be set to use for files that have a dot c extension in their filename.

    You can set that a a default setting in your Visual program. The keystrokes I've forgotten, but something like Projects tab >> default properties >> compiler options, and etc.

    <stdafx.h> is unknown to C, and would be an error or a warning, at least.

    So dump that line.

    This is what I was thinking of. Taken from your posted code, and adding a few bits.

    Code:
    #include <stdio.h>
    #include <string.h>
    
    int main (void){
    
      int i, r;
      char *p = NULL;
      char str[100];
      char str2d[12][5];
      FILE *fp = NULL;
      fp = fopen("c:\\months.txt", "r");
        
      //check if we can access the file, if not, return 1
      if( fp == NULL ){
    	printf ("cannot open file");
    	return 1;
      }
      
      r=0; //r=row, set to zero at start
      while((fgets(str, sizeof(str), fp))!= NULL) {
        //find the next comma
        if(p==NULL) {
          p=strtok(str, ",");
          strcpy(str2d[r++], p);
        }
        while((p=strtok(NULL, ","))!=NULL) {
          //put the word, into the array
          strcpy(str2d[r], p); 
          printf("\n%s", str2d[r++]);
          getchar();
        }
      }
      fclose(fp);
      printf("\n\n\t\t\t    press enter when ready");
      (void) getchar();
      return 0;
    }

  11. #11
    Registered User
    Join Date
    Sep 2010
    Posts
    17
    Code:
    	input = fopen("C:\\month.txt" , "r");
        
    	//check if we can access the file, if not, return 1
    	if( input == NULL ){
    		printf ("cannot open file");
    		return 1;
    	}
    
    	char c = '0';
    	while((c = fgetc(input)) != EOF){
    		printf("here");
    	}
    sorry for my code, i will look at your code first!
    Last edited by peterderijp; 10-11-2010 at 01:12 PM.

  12. #12
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    The tricky part is the nested while loops. If you haven't seen that used before with strtok(), it's tough to sort it out, just right - a bit unintuitive I believe. Works well though.

    You could do this same job with your non strtok() code, but you have to deal with more details, in the end - there's almost always more than one way to skin a cat, as they say.

  13. #13
    Registered User
    Join Date
    Sep 2010
    Posts
    17
    I also have to use dynamic allocation using malloc. But now i make an array, which will take a lot of memory. I think that will give some problems.

    I think i undestand what you're doing. But i think it's very difficult to do it without your array. So maybe it's a good idee to do it your way

  14. #14
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    For 12 short 3 letter words? You should have NO problem allocating that much memory.

  15. #15
    Registered User
    Join Date
    Sep 2010
    Posts
    17
    oh sorry,

    now i try to get used to the fundamentals of the assignment i have to make. I have to make an assignment with more than thousends of words. But i want to get used to the fundamentals of this kind of programming.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. from 2D array to 1D array
    By cfdprogrammer in forum C Programming
    Replies: 17
    Last Post: 03-24-2009, 10:33 AM
  2. Split up an Array
    By shanem in forum C Programming
    Replies: 6
    Last Post: 01-22-2009, 12:05 PM
  3. [question]Analyzing data in a two-dimensional array
    By burbose in forum C Programming
    Replies: 2
    Last Post: 06-13-2005, 07:31 AM
  4. Unknown Memory Leak in Init() Function
    By CodeHacker in forum Windows Programming
    Replies: 3
    Last Post: 07-09-2004, 09:54 AM
  5. Quick question about SIGSEGV
    By Cikotic in forum C Programming
    Replies: 30
    Last Post: 07-01-2004, 07:48 PM