gpt4 book ai didi

c - fread/malloc 的问题

转载 作者:行者123 更新时间:2023-11-30 18:53:22 26 4
gpt4 key购买 nike

FILE *infp, *outfp;
infp = fopen(argv[2], "r");

int len;
char *text;
fseek(infp, 0, SEEK_END);
len = ftell(infp);
printf("%d\n", len);

if ((text = (char *) malloc(500000000)) == NULL)
{
fprintf(stderr, "Error allocating memory\n");
exit(1);
}
fread(text, len, 1, infp);
text[len] = '\0';
fclose(infp);
printf("Text = %s, Address = %u\n", text, text);

返回

138
Text = , Address = 3794927632

我不确定为什么文本不打印任何内容。我是否使用了 fread 错误?

最佳答案

您需要使用rewind()fseek(3)重置文件位置像这样

FILE *infp;
FILE *outfp;
int length;
char *text;

if ((infp = fopen(argv[2], "r")) == NULL)
{
fprintf(stderr, "Error openning `%s'\n", argv[2]);
return -1;
}

fseek(infp, 0L, SEEK_END);
len = ftell(infp);
/* reset position */
fseek(infp, 0L, SEEK_SET); /* essentially rewind(infp); */

printf("%d\n", length);
if ((text = malloc(length + 1)) == NULL)
{
fprintf(stderr, "Error allocating memory\n");
return -1;
}

if (fread(text, 1, length, infp) == length)
{
text[length] = '\0';

printf("Text = %s, Address = %u\n", text, text);
free(text); /* never forget to `free' */
}
else
{
free(text);
text = NULL:
}
fclose(infp);

你也应该

  1. 检查fopen()的返回值,你永远不会检查文件是否实际打开,我认为这是主要问题。
  2. 仅分配必要的空间。
  3. 确保 fread() 没有失败。
  4. 交换 fread(3)的大小参数,首先是元素大小,然后是元素数量

    size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);

    并且返回值应等于nmemb,请阅读上面链接的手册页。

关于c - fread/malloc 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32956257/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com