Hi,
Well, I want to read the contents of file in a character array.
Actually, I am doing this for Hangman(game). I want to read the
contents of file in a character array, so that I can pick a word out
of it and then generate dashes(-) at it's place. Can anyone please
guide me on this one?
This will read a file. It is good enough for general use though not up to
the high standards of comp.lang.c, because of the use of ftell to find the
length of the file.
/*
function to slurp in an ASCII file
Params: path - path to file
Returns: malloced string containing whole file
*/
char *loadfile(char *path)
{
FILE *fp;
int ch;
long i = 0;
long size = 0;
char *answer;
fp = fopen(path, "r");
if(!fp)
{
printf("Can't open %s\n", path);
return 0;
}
fseek(fp, 0, SEEK_END);
size = ftell(fp);
fseek(fp, 0, SEEK_SET);
answer = malloc(size + 100);
if(!answer)
{
printf("Out of memory\n");
fclose(fp);
return 0;
}
while( (ch = fgetc(fp)) != EOF)
answer[i++] = ch;
answer[i++] = 0;
fclose(fp);
return answer;
}
To pick out a word, look for the first alphabetical character. Then read a
span of alphabetical characters until you hit a non-alphabetical one. Don't
forget to null-terminate your return array. Set a sensible limit such as 64
characters, and don't exceed that, so that some malicious person can't crash
your program by constructing a file with over-long words.