Go4Expert

Go4Expert (http://www.go4expert.com/)
-   C (http://www.go4expert.com/forums/c/)
-   -   fopen code required (http://www.go4expert.com/forums/fopen-code-required-t1433/)

riberet 20Sep2006 05:17

fopen code required
 
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 20Sep2006 11:05

Re: fopen code required
 
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;
}



All times are GMT +5.5. The time now is 03:33.