Joseph Martin wrote:

>       I am a subscribee to the linux-c-programming listserv. I have
> tried to send the message there several times during the last few days
> with no luck. It's not getting bounced, but I'm not recieving it back in
> my mailbox either. Could you please post it for me? (Any maybe answer too?
> :)

Done.

>       I am struggling with my long time nemesis again - strings in C. I
> have a function I'm writing that will read in a file, assign each line to
> a subscript in an array, and return the array. Problem is I can't get pass
> the returning. Suggestions welcome. Code follows. Thanks a ton.
> 
> #include <stdio.h>
> #include <stdlib.h>
> #include "file.h"
> 
> char *read_file()
> {
>       char line[10][80];
>       int i;
>       FILE *budget;
> 
>       if((budget = fopen("/home/martinja/.bashrc", "r"))==NULL) {
>               printf("Cannot open config file\n");
>               exit(1);
>       }
>       for(i=0; i<10; i++) {
>               fgets(line[i], 80, budget);
>               printf("%s", line[i]); // This tests if line reads
>                                       // correctly
>       }
>       fclose(budget);
>       return ??? //help here please!
> }

You will need to dynamically allocate the memory to store the data.
The variable `line' will vanish once you return from the function.

Also, you probably want to return a `char **' rather than `char *'.

The attached program reads each line into a temporary buffer, and then 
copies the string to dynamically allocated memory using strdup().

The array of pointers to each line is also dynamically allocated; the
array is resized as necessary using realloc().

-- 
Glynn Clements <[EMAIL PROTECTED]>


#include <stdlib.h>
#include <stdio.h>
#include <string.h>

char **read_file(const char *filename)
{
        char buff[1024];
        char **index;
        int size, count;
        FILE *fp;

        fp = fopen(filename, "r");

        if (!fp)
        {
                fprintf(stderr, "Cannot open config file\n");
                exit(1);
        }

        size = 16;
        index = malloc(size * sizeof(char *));

        for (count = 0; ; count++)
        {
                if (!fgets(buff, sizeof(buff), fp))
                        break;

                if (count >= size - 1)
                {
                        size *= 2;
                        index = realloc(index, size * sizeof(char *));
                }

                index[count] = strdup(buff);
        }

        index[count] = NULL;

        fclose(fp);

        return index;
}

int main(void)
{
        char **index;
        int i;

        index = read_file("/etc/passwd");

        for (i = 0; index[i]; i++)
                fputs(index[i], stdout);

        return 0;
}

Reply via email to