fopen code required

Discussion in 'C' started by riberet, Sep 20, 2006.

  1. riberet

    riberet New Member

    Joined:
    Sep 20, 2006
    Messages:
    1
    Likes Received:
    0
    Trophy Points:
    0
    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
     
  2. shabbir

    shabbir Administrator Staff Member

    Joined:
    Jul 12, 2004
    Messages:
    15,375
    Likes Received:
    388
    Trophy Points:
    83
    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;
    }
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice