fopen code required

riberet's Avatar, Join Date: Sep 2006
Newbie Member
Can anyone give me the code to open the file called "xyz.dat" and read the values from it and store them in two variable like x and y.

the data in this file is in this format(when opened in notepad text editor)

7.604915,6.401655
5.167884,5.786217
3.442551,8.79269
5.132062,9.018375
5.590475,6.949121
1.766262,3.432147
7.786101,3.571204
6.290994,4.194949

Each row has two values seperated by a comma(,)

I need to read these two values and assign them to some variables such as double or float.

Can someone please give me the code for the same. I'll really be grateful to that person.

Riberet
shabbir's Avatar, Join Date: Jul 2004
Go4Expert Founder
Welcome to G4EF. Here comes the code
Code:
#define MAX_LINE_SIZE 100

int main()
{
	FILE *fs;
	fs=fopen("xyz.dat","r");
	if(fs==NULL)
	{
		printf("Cannot open source file");
		return 0;
	}

	char *ch = new char[MAX_LINE_SIZE];
	while (fgets( ch, MAX_LINE_SIZE, fs ))
	{
		printf("%s",ch);
		char tmpBufX[MAX_LINE_SIZE];
		char tmpBufY[MAX_LINE_SIZE];
		for(int i = 0;ch[i] != ','; i++)
		{
			tmpBufX[i] = ch[i];
		}
		tmpBufX[i++] = '\n';
		for(int j = 0;ch[i] != '\n'; i++,j++)
		{
			tmpBufY[j] = ch[i];
		}
		tmpBufY[j] = '\n';
		double x = atof(tmpBufX);
		double y = atof(tmpBufY);
	}
	fclose(fs);
	return 0;
}