Hi all,
Just registered on the forum. I have a quick (hopefully) question. I'm trying to read from a text file into one single string. I'm having some trouble though and can't quite find my error. I have the following code below right now. The problem is that my function adds junk to the beginning and end of the string. This function must be written in C. My text file i'm testing with is a one liner:
The brown fox jumped over the lazy dog.
void readFile(char filename[20], char *string)
{
FILE *fp;
fp = fopen(filename, "r"); /* open file for input */
if (fp)
{
char c;
while(c != EOF) {
c = fgetc(fp);
//printf("%c", c);
sprintf(string, "%s%c", string, c); //apend char to our string
}
}
else /* If error occurred, display message. */
{
printf("An error occurred while opening the file.\n");
}
fclose(fp); /* close the input file */
}
however this function produces output like the following
cThe brown fox jumped over the lazy dog.
I will also note that if I uncomment the line //printf("%c", c); I get the following output:
The brown fox jumped over the lazy dog.
If anyone could help I would greatly appreciate it!
Matt