【问题标题】:Cannot assign the return value of ftell function to a char array size无法将 ftell 函数的返回值分配给 char 数组大小
【发布时间】:2020-09-04 23:18:04
【问题描述】:

我正在尝试从分配内存最少的文件中打印一些值。我使用 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���

【问题讨论】:

    标签: arrays c printf dynamic-memory-allocation ftell


    【解决方案1】:

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

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

    此外,您应该分配比文件大小多几个字节来终止空字符。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-21
      • 2019-07-24
      • 2012-10-16
      • 2021-12-29
      • 1970-01-01
      • 2014-07-17
      相关资源
      最近更新 更多