There are many things wrong.
1. It isn't written in C, C doesn't support (yet) mixed declarations and statements.
2. you don't prototype malloc by including stdlib.h
3. you free() your input before you've had a chance to use the string to open a file.
4. there's no error checking in any of your code.
5. your EOF test will likely fail because the inner assignment casts your actual EOF to a char
6. your buf has no \0 to terminate the string (when you print it with %s)
Consider
Code:
#include <stdio.h>
#include <string.h>
int main() {
char buf[BUFSIZ],ficheiro[100];
int i=0;
FILE *fp;
printf("Insira a directória do ficheiro: ");
fflush(stdout); /* make sure the prompt appears */
if ( fgets(ficheiro,sizeof(ficheiro),stdin) != NULL ) {
char *nl = strchr(ficheiro,'\n');
if ( nl != NULL ) *nl = '\0'; /* remove the newline, if present */
fp=fopen(ficheiro,"r");
if ( fp != NULL ) {
int ch;
while ( i < BUFSIZ-1 && (ch=fgetc(fp)) != EOF ) {
buf[i++] = (char)ch;
}
buf[i] = '\0';
printf("%s",buf);
fclose(fp);
}
}
return 0;
}