How to read a text file into an array line by line in C

1 Answer

0 votes
#include <stdio.h> 
#include <string.h> 

int read_text_file_into_array(char filename[], char textlines[][128]) {
    FILE* fp = fopen(filename, "r");
    if (fp == NULL) {
        printf("Could not open file %s", filename);
        return -1;
    }

    char line[80];

    int i = 0;
    while (fgets(line, sizeof(line), fp)) {
        strcpy(textlines[i++], line);
    }

    fclose(fp);

    return i;
}

int main(void)
{
    char filename[] = "d:\\data.txt";
    char textlines[1024][128];

    int totallines = read_text_file_into_array(filename, textlines);

    for (int i = 0; i < totallines; i++) {
        puts(textlines[i]);
    }

    return 0;
}



/*
run:

C is a general-purpose programming language.

It was created in the 1970s by Dennis Ritchie

and remains very widely used and influential.

C is used in operating systems' code

especially in kernels and device driver,

but can be used for any software and game development

*/

 



answered Jul 6, 2024 by avibootz

Related questions

1 answer 162 views
162 views asked Apr 8, 2021 by avibootz
1 answer 164 views
164 views asked Nov 16, 2017 by avibootz
2 answers 310 views
310 views asked Jan 4, 2021 by avibootz
2 answers 239 views
...