Thread: Fill an array with strings from file

  1. #1
    Hopeless
    Join Date
    Jul 2005
    Location
    Bay Area, CA
    Posts
    25

    Fill an array with strings from file

    Ok, so I have been tasked with a simple assignment where I must write a program that creates an array of strings, where the number of rows is specified by the user. The program reads the data from input file and sorts the array by the last name.

    This is what I have so far.

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    //// PROTOTYPE DECLARATIONS ////
    char **buildTable (void);
    int readFile (void);
    
     
    
    int main (void) //// BEGIN MAIN
    {
    	
    	char **table = buildTable (); // <-CALL TO buildTable FUNCTION
    	readFile(); // CALL TO readFile FUNCTION
    	
    	return 0;
    }
    
    
    char **buildTable (void)  //// BEGIN buildTable FUNCTION
    {
    	char **table;
    	int rowNum, row;
    
    	printf("Enter the number of rows in the table: \n");
    	scanf("%d", &rowNum);
    	table = (char **)calloc(rowNum +1, sizeof(char*));
    	if(!table) return NULL;
    	for (row = 0; row < rowNum; row++)
    	table[row] = NULL;
    	return table;
    }
    
    int readFile (void)  //// BEGIN readFile FUNCTION
    {
    	FILE *fpNames;
    
    	if ((fpNames = fopen("lab4.txt", "r")) == NULL)
    	{
    	printf("\aERROR opening lab4.txt\n");
    	return (100);
    	
    	
    	}
    	return 0;
    }
    So basically, I have a function to prompt the user to enter the amount of rows that he wants to see and that builds or allocates the memory for the array of strings. The next function opens the file and tests it to make sure it works. The question is this.

    How do I read that file into the array of strings? I know that I have to make another function to fill the array, but I do not see how each module is going to communicate with each other.

    Thanks in advance!!

  2. #2
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    You don't have to make another function. Just use fgets. The FAQ on getting a line from the user covers its use.


    Quzah.
    Hope is the first step on the road to disappointment.

  3. #3
    Hopeless
    Join Date
    Jul 2005
    Location
    Bay Area, CA
    Posts
    25
    Ok, I have been doing some more reading, and I know how to initialize a string. For example,

    Code:
    string1[] = "Monday";
    That would initialize an array called string1 that is filled with a string, "Monday". Is this correct? If this is the case, can I do the same thing by putting the file pointer in the quotes, so that it would read from the file? For example, could I do this

    Code:
    string2[] = "*fpFileName";
    Would this read from the file, FileName, or would it just put the letters *fpFileName into the string? I am guessing the latter, but hoping the first. hehe.

  4. #4
    Hopeless
    Join Date
    Jul 2005
    Location
    Bay Area, CA
    Posts
    25
    oOh ok.. I will try that out and see what I come up with. Thanks!!

  5. #5
    Hopeless
    Join Date
    Jul 2005
    Location
    Bay Area, CA
    Posts
    25
    Ok, so i modified the readfile function of my program with the fgets command and compiled it with no errors. Is there anyway to test my program to make sure that the file really is being read into string? Like, can I print something to the screen (print the file to the screen) to check to make sure it works. In theory, I would think at least, is that once the file is read into the string, I can just print the string to the screen with a "sprintf" function. Probrally totally wrong, but i guess it doesn't hurt to ask.

    Anyway, here is the modified function:

    Code:
    int readFile (void)  //// BEGIN readFile FUNCTION
    {
    	char str [80];
    	FILE *fpNames;
    
    	if ((fpNames = fopen("lab4.txt", "r")) == NULL)
    	{
    	printf("\aERROR opening lab4.txt\n");
    	return (100);	
    	
    	}
    	fgets(str, sizeof (str), stdin);
    
    	return 0;
    }

  6. #6
    Hopeless
    Join Date
    Jul 2005
    Location
    Bay Area, CA
    Posts
    25
    ok, so after a little more research, i can easily see that this last post was pretty stupid... i think... so my fgets and my str[] array are not linked in anyway. i just don't understand the syntax that is needed to get these two guys to talk to eachother. HELP!! =) Thank you!!

  7. #7
    Hopeless
    Join Date
    Jul 2005
    Location
    Bay Area, CA
    Posts
    25
    so i am going to take make a function call from the readfile function to fill the array. I know how to fill the array, and I know how to fill and array of strings, but i do not know how to do it from a file. any help?

  8. #8
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,057
    Use fgets() with your file pointer.
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

  9. #9
    Hopeless
    Join Date
    Jul 2005
    Location
    Bay Area, CA
    Posts
    25
    I'm sorry, I am still not 100% understanding this. This is what I know I have to do. I know I have a function that reads a file, then calls another function to fill an array with that file. This array will be an array of strings seeing that the file is a list of names. I know I have to use the fgets() with the file pointer, but maybe i can't seem to make it all come together. Thanks.

    Here is my code so far if it helps:

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    #define MAXELEMS 80
    
    //// PROTOTYPE DECLARATIONS ////
    char **buildTable (void);
    int readFile (void);
    char fillAry (void);
    
     
    
    int main (void) //// BEGIN MAIN
    {
    	
    	char **table = buildTable (); // <-CALL TO buildTable FUNCTION
    	readFile(); // CALL TO readFile FUNCTION
    	
    	return 0;
    }
    
    
    char **buildTable (void)  //// BEGIN buildTable FUNCTION
    {
    	char **table;
    	int rowNum, row;
    
    	printf("Enter the number of rows in the table: \n");
    	scanf("%d", &rowNum);
    	table = (char **)calloc(rowNum +1, sizeof(char*));
    	if(!table) return NULL;
    	for (row = 0; row < rowNum; row++)
    	table[row] = NULL;
    	return table;
    }
    
    int readFile (void)  //// BEGIN readFile FUNCTION
    {
    
    	FILE *fpNames;
    
    	if ((fpNames = fopen("lab4.txt", "r")) == NULL)
    	{
    	printf("\aERROR opening lab4.txt\n");
    	return (100);	
    	
    	}
    	fillAry (); //// <-- CALL TO fillAry FUNCTION	
    
    	return 0;
    }
    
    char fillAry (void)
    {
    
    // Here is where I want to fill the array with the strings from the input file with fgets().
    
    }

  10. #10
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    You still aren't allocating anything for each row. You'll have to do that in 'fillAry' I suppose. Something like:
    Code:
    void fillAry( char ** yourlist, size_t numrows )
    {
        char buf[BUFSIZ] = {0};
        FILE *fp;
        size_t row = 0;
    
        fp = fopen( "yourfile", "r" );
    
        while( fgets( buf, BUFSIZ, fp ) !=  NULL && row < numrows )
        {
            size_t len = strlen( buf );
            yourlist[ row ] = malloc( len );
            strncpy( yourlist[ row ], buf, len - 1 );
        }
    }
    That looks about right. Potentailly a few minor annoying bugs, since I didn't do any error checking, but I'll leave that up to you. Oh, and you really should call free for each row of your array when you're all done. Plus you'll have to free the whole works then too. Oh, and close your file when you're done with it.

    [edit]
    Oh, and if you want to see if it's reading correctly, just do a quick run through:
    Code:
    void readfile( void )
    {
        char buf[BUFSIZ] = {0};
        FILE *fp;
    
        fp = fopen( "yourfile", "r" );
    
        while( fgets( buf, BUFSIZ, fp ) != NULL  )
        {
            printf("This buffer contains: %s\n", buf );
        }
        fclose( fp );
    }
    Again, do some error checking.
    [/edit]


    Quzah.
    Last edited by quzah; 07-31-2005 at 11:43 PM.
    Hope is the first step on the road to disappointment.

  11. #11
    Gawking at stupidity
    Join Date
    Jul 2004
    Location
    Oregon, USA
    Posts
    3,218
    Code:
        while( fgets( buf, BUFSIZ, fp ) !=  NULL && row < numrows )
        {
            size_t len = strlen( buf );
            yourlist[ row ] = malloc( len );
            strncpy( yourlist[ row ], buf, len - 1 );
        }
    I do believe that's leaving the stored strings unterminated. You'll have to do something like this after the strncpy():
    Code:
    yourlist[row][len - 1] = '\0';
    If you understand what you're doing, you're not learning anything.

  12. #12
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Quote Originally Posted by itsme86
    I do believe that's leaving the stored strings unterminated. You'll have to do something like this after the strncpy():
    Code:
    yourlist[row][len - 1] = '\0';
    From the man page:
    The strncpy() function is similar, except that not more than n bytes of
    src are copied. Thus, if there is no null byte among the first n bytes
    of src, the result will not be null-terminated.
    Ack. Too tired. Yeah, I was thinking it was the other way around. Guess I was thinking of strcpy.


    Quzah.
    Last edited by quzah; 08-01-2005 at 12:14 PM.
    Hope is the first step on the road to disappointment.

  13. #13
    Hopeless
    Join Date
    Jul 2005
    Location
    Bay Area, CA
    Posts
    25
    hey thanks a lot for your help guys. I am going to keep working on it and I will let you know i can get it done!! again, i really appreciate it!!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. gcc link external library
    By spank in forum C Programming
    Replies: 6
    Last Post: 08-08-2007, 03:44 PM
  2. Post...
    By maxorator in forum C++ Programming
    Replies: 12
    Last Post: 10-11-2005, 08:39 AM
  3. Dikumud
    By maxorator in forum C++ Programming
    Replies: 1
    Last Post: 10-01-2005, 06:39 AM
  4. Reading strings from a file and storing into an array
    By Rizage in forum C++ Programming
    Replies: 1
    Last Post: 10-24-2002, 03:04 AM
  5. simulate Grep command in Unix using C
    By laxmi in forum C Programming
    Replies: 6
    Last Post: 05-10-2002, 04:10 PM