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,885 questions

51,811 answers

573 users

How to read lines from a text file without knowing the lines length in C

1 Answer

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

int main() {
    FILE* fp = NULL;
    char filename[32] = "d:\\data.txt";

    fopen_s(&fp, filename, "r");
    if (fp == NULL) {
        fprintf(stderr, "fopen() error\n");
        return -1;
    }

    int MAXLEN = 4095;
    char* buffer = (char*)malloc(sizeof(char) * MAXLEN);
    if (buffer == NULL) {
        printf("%s", "malloc error");
        return -1;
    }

    int ch;
    int length = 0;
    char* tmp = NULL;

    while ((ch = fgetc(fp)) != EOF) {
        if (length == MAXLEN) {
            MAXLEN *= 2; 
            tmp = realloc(buffer, MAXLEN * sizeof(char));
            if (tmp == NULL) {
                printf("%s", "realloc error");
                return -1;
            }
            else {
                buffer = tmp;
            }
        }
        buffer[length] = ch;
        length++;
    }
    buffer[length] = '\0';

    puts(buffer);

    free(buffer);
    fclose(fp);
}




/*
run:

C is a general-purpose programming language.
It was created in the 1970s by Dennis Ritchie,
and remains very widely used and influential...

*/

 



answered Jan 19, 2025 by avibootz

Related questions

2 answers 212 views
1 answer 163 views
2 answers 226 views
1 answer 218 views
1 answer 237 views
...