In C, how should I read a text file and print all strings

Viewed 734768

I have a text file named test.txt

I want to write a C program that can read this file and print the content to the console (assume the file contains only ASCII text).

I don't know how to get the size of my string variable. Like this:

char str[999];
FILE * file;
file = fopen( "test.txt" , "r");
if (file) {
    while (fscanf(file, "%s", str)!=EOF)
        printf("%s",str);
    fclose(file);
}

The size 999 doesn't work because the string returned by fscanf can be larger than that. How can I solve this?

9 Answers

You can use getline() to read your text file without worrying about large lines:

getline() reads an entire line from stream, storing the address of the buffer containing the text into *lineptr. The buffer is null-terminated and includes the newline character, if one was found.

If *lineptr is set to NULL before the call, then getline() will allocate a buffer for storing the line. This buffer should be freed by the user program even if getline() failed.

bool read_file(const char *filename)
{
    FILE *file = fopen(filename, "r");
    if (!file)
        return false;
    
    char *line = NULL;
    size_t linesize = 0;

    while (getline(&line, &linesize, file) != -1) {
        printf("%s", line);
        free(line);
    }
    
    free(line);
    fclose(file);

    return true;
}

You can use it like this:

int main(void)
{
    if (!read_file("test.txt")) {
        printf("Error reading file\n");
        exit(EXIT_FAILURE);
    }
}

I use this version

char* read(const char* filename){
    FILE* f = fopen(filename, "rb");
    if (f == NULL){
        exit(1);
    }
    fseek(f, 0L, SEEK_END);
    long size = ftell(f)+1;
    fclose(f);
    f = fopen(filename, "r");
    void* content = memset(malloc(size), '\0', size);
    fread(content, 1, size-1, f);
    fclose(f);
    return (char*) content;
}
Related