Created
January 13, 2017 21:11
-
-
Save sachintha81/22ba7946f419601cc815cec2f4ce9f4d to your computer and use it in GitHub Desktop.
Reading a Text File into a 2D Array in C
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
int main(int argc, char *argv[]) | |
{ | |
// Allocate memory for the array like this: | |
int** array; | |
array = malloc(n * sizeof(*array)); /* Assuming `n` is the number of rows */ | |
if(!array) /* If `malloc` failed */ | |
{ | |
fputs(stderr, ""Error allocating memory; Bailing out!""); | |
exit(-1); | |
} | |
int count = 1; | |
for(int i = 0; i < n; i++) | |
{ | |
array[i] = malloc(count * sizeof(**array)); | |
if(!array[i]) /* If `malloc` failed */ | |
{ | |
for(int j = 0; j < i; j++) /* free previously allocated memory */ | |
{ | |
free(array[j]); | |
} | |
free(array); | |
fputs(stderr, ""Error allocating memory; Bailing out!""); | |
exit(-1); | |
} | |
count++; | |
} | |
// Then, read data from the file into the array by using: | |
FILE* fp = fopen(""file.txt"", ""r""); | |
if(!fp) | |
{ | |
for(int i = 0; i < n; i++) /* free previously allocated memory */ | |
{ | |
free(array[i]); | |
} | |
free(array); | |
fputs(stderr, ""Error opening 'file.txt'; Bailing out!""); | |
exit(-1); | |
} | |
int max = 1; | |
for(int i = 0; i < n; i++) | |
{ | |
for(count = 0; count < max; count++) | |
{ | |
fscanf(fp, ""%d"", &array[i][count]); | |
} | |
max++; | |
} | |
// Then print the results: | |
max = 1; | |
for(int i = 0; i < n; i++) | |
{ | |
for(count = 0; count < max; count++) | |
{ | |
printf(""array[%d][%d] = %d"", i, count, array[i][count]); | |
} | |
max++; | |
} | |
// And finally, free the allocated memory: | |
for(int i = 0; i < n; i++) | |
{ | |
free(array[i]); | |
} | |
free(array); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
PROBLEM STATEMENT
I have a text file that looks like the following.
Basically, row 1 has 1 element, row 2 has 2 elements, row 3 has 3 elements, ... up to n rows with n elements.
I need to read them, and put into a 2-d array in this fashion:
You get the drift.
However I know n (the number of rows) only at run time. How would I go about reading the file into a 2x2 array?
StackOverflow post:
http://stackoverflow.com/questions/33579813/reading-a-text-file-into-a-two-dimentional-array-in-c