0

I am trying to read from a text file and assign that to a variable. At the moment I have it at the stage where it reads from the file and prints it out, however I haven't figured out how to assign the result to a variable.

This is my code:

int c;
FILE *file;
file = fopen(inputFilename, "r");
if (file) {
    while ((c = getc(file)) != EOF) {
        putchar(c);
    }
    fclose(file);
}

I'm not entirely sure what putchar(c) means but I assume it is just printing out the characters one at a time?

How would I go about trying to achieve what I am looking to do?

user3746428
  • 11,047
  • 20
  • 81
  • 137

1 Answers1

2

What you mean is to get the whole file content, that is easily done this way

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

char *readFileContent(const char *const filename)
{
    size_t size;
    FILE  *file;
    char  *data;

    file = fopen(filename, "r");
    if (file == NULL)
    {
        perror("fopen()\n");
        return NULL;
    }

    /* get the file size by seeking to the end and getting the position */
    fseek(file, 0L, SEEK_END);
    size = ftell(file);
    /* reset the file position to the begining. */
    rewind(file);

    /* allocate space to hold the file content */
    data = malloc(1 + size);
    if (data == NULL)
    {
        perror("malloc()\n");
        fclose(file);
        return NULL;
    }
    /* nul terminate the content to make it a valid string */
    data[size] = '\0';
    /* attempt to read all the data */
    if (fread(data, 1, size, file) != size)
    {
        perror("fread()\n");

        free(data);
        fclose(file);

        return NULL;
    }
    fclose(file);
    return data;
}

int main()
{
    char *content;

    content = readFileContent(inputFilename);
    if (content != NULL)
    {
        printf("%s\n", content);
        free(content);
    }
    reutrn 0;
}

and this will of course fail in the rare case where the file size exceeds the available RAM, but it will not cause undedined behavior, because that case is handeled as a malloc() failure.

Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97