Reputation:
how to instead of
char text[10000];
do
char text[fp_len];
i also get this warning:
warning: value computed is not used
FILE *fp;
fp = fopen(path, "r");
int fp_len;
fseek(fp, 0, SEEK_END)+1;
fp_len = ftell(fp);
fseek(fp, 0, SEEK_SET);
printf("%d---", fp_len);
char text[10000];
fread(text, fp_len, 1, fp);
printf("%s", text);
should i also add:
text[]= '\0'
to the bottom. ( above printf )
Upvotes: 1
Views: 204
Reputation: 140287
as noted in comments fseek(fp, 0, SEEK_END)+1
is just adding the return code of fseek
to 1 (why would you do that?), and the result (useless) is dropped.
Now, you could create a variable length array (perfectly legal in C) using char text[fp_len];
, that would work, but generally auto variable space is not designed to be big, so you can have "stack overflow" if the file is too big: in that case char *text = malloc(fp_len)
is preferred.
If you want to null-terminate it (which is useful only if you want to printf
the contents of the file, and if the file contains text), don't forget to add 1 to your buffer so you can legally do text[fp_len] = '\0';
Aside: fseek(fp, 0, SEEK_SET);
could be just rewind(fp);
Upvotes: 1
Reputation: 7441
You get warning of unused value because when you add +1 to returned value, you are doing nothing
fseek(fp, 0, SEEK_END)+1;
is evaluated to
fseek(fp, 0, SEEK_END);
But compiler warns you about, maybe you forgot to assign result somewhere.
To read data, reserve memory in HEAP region using dynamic allocation otherwise you may enter to stack overflow if your fp_len
is too big.
char *text = malloc(sizeof(*text) * (fp_len + 1));
And don't forget to include stdlib.h
Upvotes: 1