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. I did 3 approaches and one of them was successful. 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:
#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.
Also you should allocate a few bytes more than the size of file for terminating null-character.