to********@gmail.com said:
How do I get fscanf to copy into an array?
One element at a time.
I also need to use malloc,
but where do I put it in my file?
At the point where you first need the memory. Be sure to #include <stdlib.h>
for the malloc prototype.
FILE *ifp;
char c;
int y = 0;
txtFile = (char *) malloc(FILELENGTH * sizeof(char)) ;
txtFile = malloc(FILELENGTH * sizeof *txtfile);
if(txtFile != NULL)
{
>
printf ("Enter the name of the file to analyze : ");
gets (filename);
Don't use gets. It's a buffer overflow waiting to happen. Instead, use
fgets, find the newline using strchr, and overwrite it with '\0' if it's
found. (If it's not found, you probably don't want to accept the filename
anyway.)
printf ("\n");
ifp = fopen(filename, "r");
if (ifp == NULL)
{
fprintf (stderr, "Error opening file\n");
exit (-2);
}
while(fscanf (ifp, "%c", &c) != EOF)
I recommend == 1 rather than != EOF. fscanf returns the number of fields
successfully converted, and you're expecting one field, so that's what you
should test for.
{
txtFile[y] = c;
y++;
}
This is fine provided y never equals or exceeds the array bound. But, to
answer your question(!), you can instead do this:
y = 0;
while(y < FILELENGTH && fscanf(ifp, "%c", &txtFile[0]) == 1)
{
y++;
}
if(y == FILELENGTH)
{
you ran out of buffer, but at least no harm was done.
}
If you plan to use txtFile as a string, don't forget to null-terminate it,
which entails leaving space for a null terminator:
y = 0;
while(y < FILELENGTH - 1 && fscanf(ifp, "%c", &txtFile[0]) == 1)
{
y++;
}
if(y == FILELENGTH - 1)
{
you ran out of buffer, but at least no harm was done.
}
else
{
txtFile[y] = '\0';
}
--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at above domain (but drop the www, obviously)