[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

Re: programming



* Sebastiaan <S.Breedveld@ITS.TUDelft.NL> spake thus:
> High,
> 
> 
> On Sun, 4 Nov 2001, J.A.Serralheiro wrote:
> 
> > hi. Im trying to read a complete line from a text file.
> > I use the  fscanf( file, "[^\n]",buffer);  butit doesnt work. I reads the
> > entire file until overflow of the buffer.
> > 
> > Can some one tell me how?
> > 
> > I read scanf manual, but it wasnt of much help, for me at leastr.
> > 
> >From an old proggie I wrote once:
> while (fgets(buff, sizeof(buff)-1, filestream) != NULL)
>         {
> 	/* do something with the 'buff' variable */
> 	}

/* in the simple case of reading a line from a file, this will work: */
int main(void)
{
	char s[80];
	FILE *fp;

	if (!(fp = fopen("filename", "r"))) {
		puts("error opening file");
		return -1;
	}
	
	fgets(s, sizeof s, fp);
	
	puts(s);

	return 0;
}

Beware though, if you want to put your readline stuff in a function
different from the one that declared the array, you have to pass the
size of the array, e.g. thusly:

void f(char *s, int lim);

#define LEN 80
int main(void)
{
	char s[LEN];
	
	f(s, LEN);
	puts(s);
	
	return 0;
}

void f(char *s, int lim)
{
	FILE *fp;

	if (!(fp = fopen("filename", "r"))) {
		puts("error opening file");
		return -1;
	}
	
	fgets(s, lim, fp);
}

Hope that helps.

Regards,
Stig

-- 
brautaset.org
Registered Linux User 107343



Reply to: