Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,907 questions

51,839 answers

573 users

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 151 views
151 views asked Apr 8, 2021 by avibootz
1 answer 154 views
154 views asked Nov 16, 2017 by avibootz
2 answers 285 views
285 views asked Jan 4, 2021 by avibootz
2 answers 223 views
...