0

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

1 回答 1

3

您在寻找到文件末尾后忘记将文件位置移回,从而阻止读取文件的内容。

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

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

于 2020-09-04T23:20:12.137 回答