无法将 ftell 函数的 return 值分配给 char 数组大小

Cannot assign the return value of ftell function to a char array size

我正在尝试从分配了最少内存的文件中打印一些值。我使用 ftell() 来查找文件,从而最大限度地减少使用的内存。 我做了 3 种方法,其中一种成功了。我不知道为什么其他 2 个不打印到字符串,因为它们似乎与成功代码类似。

以下字符串位于我尝试输出的文件中

123\n45 678

我的尝试:

成功

#include <stdio.h>
int main()
{
    int size = 15;
    char arr[size];

    FILE *pf = fopen(".txt", "r");

    fgets(arr, size, pf);

    puts(arr);

    fclose(pf);
    return 0;
}

失败:

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

    int main()
    {
        FILE *pf = fopen(".txt", "r");
        int check = fseek(pf, 0, SEEK_END);
        if (check)
        {
         

   printf("could not fseek\n");
    }
    unsigned size = 0;
    size = ftell(pf);

    char *arr = NULL;
    arr = (char *)calloc(size, sizeof(char));

    if (arr == NULL)
    {
        puts("can't calloc");
        return -1;
    }

    fgets(arr, size, pf);
    puts(arr);

    free(arr);
    return 0;
}

输出:没有打印出来

失败#2:

#include <stdio.h>
int main()
{

    FILE *pf = fopen(".txt", "r");

    int check = fseek(pf, 0, SEEK_END);
    if (check)
    {
        printf("could not fseek\n");
    }
    int size = 0;
    size = ftell(pf);
    char arr[size];

    fgets(arr, size, pf);

    puts(arr);

    fclose(pf);

    return 0;
}

输出:一些垃圾

0Y���

您在查找到文件末尾后忘记将文件位置移回,导致无法读取文件内容。

size = ftell(pf);
fseek(pf, 0, SEEK_SET); /* add this */

另外你应该分配比文件大小多几个字节来终止null-character。