In: Computer Science
C Programming
How do you read in a text file line by line into a an array.
example, i have the text file containing:
line 1: "qwertyuiop"
line 2: "asdfghjkl"
line 3: "zxcvbnm"
Then in the resulting array i get this:
array:"qwertyuiopasdfghjklzxcvbnm"
//C program for gcc (GCC) 9.3.0 and above
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main()
{
FILE *fp = fopen("input.txt","r");
char *line = NULL;
size_t len = 0;
ssize_t read;
if(fp==NULL)
{
printf("Error Opening
File!!");
}
int i;
char *arr = (char *)malloc(sizeof(char)*5000);
while ((read = getline(&line, &len, fp)) !=
-1) {
strcat(arr, line);
}
printf("%s",arr);
}