Function to read content of a file an store in an array

Viewed 38

I am trying to write a function that will read contents of a file and return an array of string of those contents. A single line will be a single element in the array, so if there are 10 lines in the file, then there will be 10 elements in the new string array. You can assume that the file contains only numbers(one number per line):

/**
 * read_file - reads the content of a file
 * @path: The name of the file to be opened
 *
 * Description: This function will assume that all the contents of
 * the file specified by pathname will be numbers(on number per line)
 *
 * Return: On success, it returns an array of strings containing
 * the contents of the file
 */
char **read_file(char *path, int *num)
{
        FILE *fd;
        char *lineptr = NULL;
        size_t n = 0;
        char **str_num_arr = NULL;
        int  i = 0;

        fd = fopen(path, "r");

        if (fd == NULL)
        {
                fprintf(stderr, "Error: unable to open file %s\n", path);
                exit(EXIT_FAILURE);
        }
        *num = num_line(fd); // num_line finds the number of lines in the file
        str_num_arr = (char **)malloc(sizeof(char *) * (*num));
        if (str_num_arr == NULL)
        {
                fprintf(stderr, "Error: malloc failed");
                exit(EXIT_FAILURE);
        }
        while (getline(&lineptr, &n, fd) != -1)
        {
                str_num_arr[i] = (char *)malloc(sizeof(char) * (strlen(lineptr) + 1));
                strcpy(str_num_arr[i], lineptr);
                i++;
        }
        return (str_num_arr);
}

Here is a test case:

/**
 * main - Entry point for my program
 * @ac: The number of command line arguments
 * @av: An array that holds the command line arguments as
 * string a string array
 *
 * Return: On success, it returns 0. On faliure, it returns
 * -1.
 */
int main(int ac, char **av)
{
        char **num_str;
        int n = 0, i;

        if (ac != 2)
        {
                fprintf(stderr, "Usage: ./factors <file_name>\n");
                exit(EXIT_FAILURE);
        }
        num_str = read_file(av[1], &n);
        for (i = 0; i < n; i++)
        {
                fprintf(stdout, "%s", num_str[i]);
        }
        exit(EXIT_SUCCESS);
}

$ cat test
4
12
34
128
1024
4958
1718944270642558716715
9
99
999
9999
9797973
49
239809320265259

When I compile and run I get a Segmentation fault(core dumped) error.

Why I am I getting a Segmentation fault(core dumped) error. I have allocated enough memory for the array that will hold the string, the number of lines in the file will be equal to the number of elements of the array. Is it the way I am accessing the array elements and assigning them?

0 Answers
Related