Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #define MROWS 100
- #define MCOLS 20
- int main (int argc, char **argv) {
- if (argc < 2) {
- fprintf (stderr, "error: insufficient input. usage: %s filename\n", argv[0]);
- return 1;
- }
- FILE *fp = fopen (argv[1], "r");
- if (!fp) {
- fprintf (stderr, "error: file open failed for '%s'.\n", argv[1]);
- return 1;
- }
- char *line = NULL; /* NULL forces getline to allocate */
- size_t n = 0; /* max chars to read (0 - no limit) */
- ssize_t nchr = 0; /* number of chars actually read */
- int **array = NULL; /* array of ptrs to array of int */
- size_t ridx = 0; /* row index value */
- size_t cidx = 0; /* col index value */
- char *endptr = NULL; /* endptr to use with strtol */
- /* allocate MROWS (100) pointers to array of int */
- if (!(array = calloc (MROWS, sizeof *array))) {
- fprintf (stderr, "error: array allocation failed\n");
- return 1;
- }
- /* read each line in file */
- while ((nchr = getline (&line, &n, fp)) != -1)
- {
- /* strip newline or carriage return (not req'd) */
- while (line[nchr-1] == '\r' || line[nchr-1] == '\n')
- line[--nchr] = 0;
- if (!nchr) /* if line is blank, skip */
- continue;
- /* allocate MCOLS (20) ints for array[ridx] */
- if (!(array[ridx] = calloc (MCOLS, sizeof **array))) {
- fprintf (stderr, "error: array[%zd] allocation failed\n", ridx);
- return 1;
- }
- cidx = 0; /* reset cidx */
- char *p = line; /* assign pointer to line */
- /* parse each int in line into array */
- while ((array[ridx][cidx] = (int)strtol (p, &endptr, 10)) && p != endptr)
- {
- /* checks for underflow/overflow omitted */
- p = endptr; /* increment p */
- cidx++; /* increment cidx */
- /* test cidx = MCOLS & realloc here */
- }
- ridx++; /* increment ridx */
- /* test for ridx = MROWS & realloc here */
- }
- /* free memory and close input file */
- if (line) free (line);
- if (fp) fclose (fp);
- printf ("\nArray:\n\n number of rows with data: %zd\n\n", ridx);
- /* reset ridx, output array values */
- ridx = 0;
- while (array[ridx])
- {
- cidx = 0;
- while (array[ridx][cidx])
- {
- printf (" array[%zd][%zd] = %d\n", ridx, cidx, array[ridx][cidx]);
- cidx++;
- }
- ridx++;
- printf ("\n");
- }
- /* free allocated memory */
- ridx = 0;
- while (array[ridx])
- {
- free (array[ridx]);
- ridx++;
- }
- if (array) free (array);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement