I was trying to read a file into a string with the following code. I assigned 5 bytes for the char *a
and actually read a file with more than 5 chars. However, the output still print the correct file contents without any garbage value or missing value.
#include <stdio.h>
#include <stdlib.h>
#define INPUT_SIZE 5
int main() {
char *a = malloc(INPUT_SIZE);
FILE *fp = fopen("text", "r");
if (fp == NULL) {
perror("Unable to open the file");
}
char *b = a;
char c;
int i = 0;
while ((c = fgetc(fp)) != EOF) {
*b++ = c;
}
printf("%s", a);
free(a);
fclose(fp);
return 0;
}
The input file is
abc
def
g
And the output is exactly the same as the input file.
Since normally there should be a '\0' at the end of the char *
to show where the string end. But in this occasion, there is no explicit '\0' in the char *a
. So I wonder if there is an '\0' at the end of the file which was read as the last char ?