[英]Cannot assign the return value of ftell function to a char array size
I am trying to print some values from a file with minimum allocated memory.我正在尝试从具有最小分配内存的文件中打印一些值。 I have used ftell() to find out the file, thus, to minimize used memory.
我已经使用 ftell() 找出文件,从而最大限度地减少使用的内存。 I did 3 approaches and one of them was successful.
我做了 3 种方法,其中一种是成功的。 I am clueless why 2 others do not print to the string since they seem to be analogical to the successful code.
我不知道为什么另外两个不打印到字符串,因为它们似乎与成功的代码类似。
The following string is located in the file that I attempt to output以下字符串位于我尝试输出的文件中
123\n45 678
My attempts:我的尝试:
Successful成功的
#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;
}
Fail:失败:
#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;
}
output: nothing prints out输出:没有打印出来
Fail #2:失败 #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;
}
output: some garbage输出:一些垃圾
0Y���
You forgot to move the file position back after seeking to the end of file, preventing from reading the contents of file.查找到文件末尾后忘记将文件位置移回,导致无法读取文件内容。
size = ftell(pf);
fseek(pf, 0, SEEK_SET); /* add this */
Also you should allocate a few bytes more than the size of file for terminating null-character.此外,您应该分配比文件大小多几个字节来终止空字符。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.