I'm learning about file input/output in C. But there is something I don't understand.
I was about to print the simple sentence in the [words.txt] using fgets, but it doesn't work.
[words.txt] as below:
This speech caused a remarkable sensation among the party.
And my code is :
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char *buffer = malloc(100);
memset(buffer, 0, 100);
FILE *fp = fopen("words.txt", "r");
fgets(buffer, sizeof(buffer), fp);
printf("%s\n", buffer);
fclose(fp);
free(buffer);
return 0;
}
The output is "This sp"
I thought there was no problem with my code, but the output result was unexpected.
I mean,
why isn't the whole string printing out?
Also, what is the reason for this output string?
(There seems to be no indication that this code will have 7 character,that is, "This sp")
Since you declared
bufferaschar *buffer, it is not an array. Instead, it is simply a pointer.The expression
sizeof bufferwill evaluate to the size of the pointer itself, not the size of the object that the pointer is pointing to. Since pointers typically have a size of 32 or 64 bits, the expressionsizeof bufferwill evaluate to either4or8. In your case, it seems to be8.If you had declared
bufferinstead like thisthen
bufferwould not be a pointer, but an array, and the expressionsizeof bufferwould have evaluated to100.In your case, there is nothing wrong with using
malloc, instead of an array. However, if you usemalloc, you must remember the size of the allocated memory yourself. You cannot use thesizeofoperator for this.Instead of writing the number
100in several places in your code, you can use a preprocessor macro for this:This has the advantage that if you ever decide to change the number
100to some other number, you only have to change the number in one place in your code, instead of several places.