this program should take in input a number n and so create n triangles. After, I want to write this triangles in a file and to print this file on standard output. I don't understand why if I input n = 2 the program prints only one triangle's coordinates. Moreover if I input coordinates: 1.0,1.1-1.5,1.6-2.4,2.5 for the triangle's vertices, output is 2.4,2.5-0.0,0.0-0.0,0.0. Can someome help me?
#include <stdio.h> #include <stdlib.h> #include <math.h> typedef struct{ float x; float y; } Punto; typedef struct{ Punto p1; Punto p2; Punto p3; } Triangolo; Punto creaPunto(); void creaTriangolo(Triangolo *); void stampaPunto(Punto); void stampaTriangolo(Triangolo); void creaFileTriangoli(char[], int); void stampaFileTriangolo(char[]); Punto creaPunto(){ Punto p; printf("Inserire la coordinata x: "); scanf("%f", &p.x); printf("Inserire la coordinata y: "); scanf("%f", &p.y); return p; } void creaTriangolo(Triangolo *t){ printf("Triangolo.\n"); printf("Vertice p1:\n"); t->p1 = creaPunto(); printf("Vertice p2:\n"); t->p2 = creaPunto(); printf("Vertice p3:\n"); t->p3 = creaPunto(); } void stampaPunto(Punto v){ printf("Coordinata x: %f\n", v.x); printf("Coordinata y: %f\n", v.y); } void stampaTriangolo(Triangolo t){ printf("Triangolo\n"); printf("Vertice p1:\n"); stampaPunto(t.p1); printf("Vertice p2:\n"); stampaPunto(t.p2); printf("Vertice p3:\n"); stampaPunto(t.p3); } void creaFileTriangoli(char f[], int n){ FILE *ptr; Triangolo t; int i; ptr = fopen(f, "wb"); if(ptr == NULL){ printf("File inesistente.\n"); } else{ for(i=0; i<n; i++){ creaTriangolo(&t); fwrite(&t, sizeof(Triangolo), 1, ptr); } } } void stampaFileTriangolo(char f[]){ FILE *ptr; Triangolo t; ptr = fopen(f, "rb"); if(ptr == NULL){ printf("File inesistente.\n"); } else{ fseek(ptr, sizeof(Triangolo), SEEK_SET); while(!feof(ptr)){ fread(&t, sizeof(Triangolo), 1, ptr); stampaTriangolo(t); } fclose(ptr); } } int main(int argc, char *argv[]) { FILE *ptr; char f[300] = "C:\\sole.dat"; Triangolo t; int n; float perimetro; printf("Inserire il numero di triangoli da analizzare: "); scanf("%d", &n); creaFileTriangoli(f,n); stampaFileTriangolo(f); return 0; }
fwrite()orfread()- and you also need to check the return value fromfclose(). How do you know thefwrite()calls succeeded?fseek(ptr, sizeof(Triangolo), SEEK_SET);? This line causes you to skip the first triangle.fseek. I try to delete it,but output is the same.