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 Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Please help, can't read a .txt file

Status
Not open for further replies.

karakatiza

Technical User
Feb 7, 2004
1
US
Hello:

My program outputs data into a .txt file in a following format:
1234
2345
3456
4567

I need to be able to read a particular number from the file (let's say number 4 in the second row) and assign that number to a variable. Help me out please, I have no idea how to make this work. Thanks a lot.
 
you can use the function "fscanf" to do it,here is an example on how you could proceed:
Code:
#include <stdio.h>

void main()
{
	int number, lines = 1;
	FILE *fp = fopen(&quot;data.txt&quot;,&quot;r&quot;);
	if(!fp) 
	{ 
		perror(&quot;data.txt&quot;); 
		return; 
	}
	while( fscanf( fp, &quot;%d&quot;, &number ) != EOF )
	{
		if( lines == 4 ) break;
		lines++;
	}
	printf(&quot;number = %d\n&quot;,number);
	fclose(fp);
}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top