Mindtrip
Mindtrip

Reputation: 33

Creating txt file and reading from it

I tried to create mydata.txt and read from it but compiler gives results as

0.000000
0.000000
168
2686832

What is wrong with this code?

int main()
{
    double f_1, f_2;
    int i_1, i_2;
    FILE *file_pointer;
    char file_name[SIZE] = "mydata.txt";

    file_pointer = fopen(file_name, "w");
    fprintf(file_pointer, "%f %f %d %d", 23.556, -76e5, 76, 5);

    file_pointer = fopen(file_name, "r");
    fscanf(file_pointer, "%lf %lf %ld %ld", &f_1, &f_2, &i_1, &i_2);

    fclose(file_pointer);

    printf("%f\n", f_1);
    printf("%f\n", f_2);
    printf("%d\n", i_1);
    printf("%d\n", i_2);

    getch();

    return 0;
}

Upvotes: 0

Views: 89

Answers (1)

CiaPan
CiaPan

Reputation: 9570

Do fclose() before the second fopen().

Upvotes: 4

Related Questions