Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Passing text from a file to an array??

Status
Not open for further replies.

lbucko

Programmer
Feb 13, 2002
11
0
0
IE
How do I read in text from a file into an array I have tried the following:
Code:
while(fgets(phrase, 100, ffp))
but this doesn't seem to work, I want to read in from the a file with file pointer ffp, into array phrase.

I also tried to do it the following way:
Code:
int status = fscanf(ffp, "%c", phrase);
while(status != EOF)
This won't work though as I'm only reading a character, how do I get it to take more than a character?? Any help please!
 
Here is a little example to illustrate how you can do this:

int main(int argc, char* argv[])
{
FILE *fp;
if(( fp = fopen( "dialogs.txt", "r" )) == NULL )
printf(" can't open the file \"dialogs.txt\"");
char Buffer[4096];
char c;
int i = 0;
while(( c = getc( fp )) != EOF )
{
Buffer = c;
i++;
}
for( int j = 0; j < i; j++ )
printf(&quot;%c&quot;,Buffer[j]);
fclose(fp);
return 0;
}
 
Just for completeness, you will want to avoid
a buffer overflow as well...

...
int maxbuf;
int i = 0;
...
maxbuf=(int)(sizeof(Buffer)-1);
while(( c = getc( fp )) != EOF )
{
Buffer = c;
i++;
if( i >= maxbuf )
break;
}
...

You could also perform this check in the &quot;while()&quot; statement
directly if you like....
while((( c = getc( fp )) != EOF) && i < maxbuf )

However, all this is really moot since a better
way to do this is with &quot;fread()&quot;...

memset((void *)Buffer, '\0', sizeof(Buffer)); // init. the buffer
while((fread(Buffer, sizeof(Buffer)-1, 1, ffp)) > 0)
{
...process the buffer...
memset((void *)Buffer, '\0', sizeof(Buffer)); // re-init. the buffer
}

fread does not distinguish between end-of-file and error,
and callers must use feof(3) and ferror(3) to determine
which occurred.
 
If you want to avoid reading the text file one character at a time...try the following:

Code:
if ((hInFile=fopen(&quot;./test.txt&quot;, &quot;r&quot;)) == NULL) {
	printf(&quot;Couldn't open file.\n&quot;);
}

while (!feof(hInFile)) {
	memset (sString, '\0', 100);
	fgets(sString, 100, hInFile);
	...
}[code]

->fgets will read until it reads 99 characters or a newline.
 
If you want to avoid reading the text file one character at a time...try the following:

Code:
char		sString[100];

if ((hInFile=fopen(&quot;./test.txt&quot;, &quot;r&quot;)) == NULL) {
	printf(&quot;Couldn't open file.\n&quot;);
}

while (!feof(hInFile)) {
	memset (sString, '\0', 100);
	fgets(sString, 100, hInFile);
	...
}[code]

->fgets will read until it reads 99 characters or a newline.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top