简体   繁体   中英

Reading lines from stdin into 2d array in C without knowing length of lines

I want to read lines from stdin with variable length until the end of input. The example input would be something like this:

#.###############
#...#...........#
#.###.#####.#.###
#...........#...#
###############.#

but with various lengths of rows and columns.

What is the best way to read it into 2d array except for reading it as chars?

Assuming you're running on a POSIX-compliant system, you can use the getline() function to read lines of almost arbitrary length (only limited by available memory). Something like this should work:

char *line = NULL;
size_t bytes = 0UL;

for ( int ii = 0;; ii++ )
{
    ssize_t bytesRead = getline( &line, &bytes, stdin );
    if ( bytesRead <= 0L )
    {
        break;
    }

    lineArray[ ii ] = strdup( line );
}

free( line );

You'll have to add error checking and take care of lineArray yourself.

char *buff = malloc(1024 * 100); // 100K should be plenty, tweak as desired.
char *maze = 0;
int width = 0, 
int height = 0;    

FILE *fp = fopen(input.txt, "r");
fgets(buff, 1024 * 100, fp);
if(!strchr(buff, '\n'))
   goto failed_sanity_test;
striptrailingwhitespace(buff);
if(height == 0)
   width = strlen(buff);
/* sanity-test width ? */
else
   if(strlen(buff) != width)
       goto ragged_edge_maze;
temp = realloc(maze, width * (height + 1));
if(!temp) 
  goto out_of_memory;
maze = temp;
memcpy(maze + height * width, buff, width);
height++;

Its fiddly in C in comparison to many other langues, but at least you have full control of the error conditions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM