如何将文本文件数据分配给变量

How to assign text file data to variable

我正在尝试从文本文件中读取并将其分配给一个变量。目前我在从文件读取并打印出来的阶段拥有它,但是我还没有想出如何将结果分配给变量。

这是我的代码:

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

我不完全确定 putchar(c) 是什么意思,但我认为它只是一次打印出一个字符?

我将如何努力实现我想要做的事情?

你的意思是获取整个文件内容,这样很容易做到

#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] = '[=10=]';
    /* 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;
}

在文件大小超过可用 RAM 的极少数情况下,这当然会失败,但不会导致意外行为,因为这种情况被视为 malloc() 失败。