C Programming File I/O -
i'm trying read text file , write one, every time execute code, nothing happens text files. "nothing happens", mean program won't read input file , no data exported output file. point out why not working? given in advance. here code:
#include <stdio.h> #include <stdlib.h> file *inptr, *outptr; int main() { int a, b, c; inptr = fopen("trianglein.txt","r"); //initialization of pointer , opening of file trianglein.txt outptr = fopen("triangleout.txt","w"); //initialization of pointer , opening of file triangleout.txt while((fscanf(inptr,"%d %d %d",&a, &b, &c))!= eof){ fprintf(outptr,"\n%2d %2d %2d\n",a,b,c); if(a+b>c && b+c>a && c+a>b){ fprintf(outptr, "this triangle.\n"); if(a !=b && b !=c && a!=c){ fprintf(outptr, "this scalene triangle.\n"); if(a==b && a==c && c==b){ fprintf(outptr, "this equilateral triangle.\n"); if(a*a+b*b==c*c || b*b+c*c==a*a || a*a+c*c==b*b){ fprintf(outptr, "this right trianlge.\n"); } } } } } return 0; }
trianglein.txt
contents:
10 12 15 2 3 7 3 4 5 6 9 5 6 6 6 6 8 10 7 7 9
multiple problems.
firstly, need check if inptr , outptr valid testing against null.
secondly, fscanf can return either eof, 0 or > 0.
if input file doesn't contain valid input.
also there problems in can 3 ints read successfull, or 2 ints or 1 , value of a, b , c optionally set.
if no conversion took place on input value of 0 returned in case while loop exit.
also bear in mind scanf style functions input succeed , return value of 1.
"1rubbish"
i think may want following:
// somewhere near top #include <stderr.h> // ... other includes const char* inname = "trianglein.txt"; const char* outname = "triangleout.txt"; // other stuff // inside main... // initialization of pointer , opening of file trianglein.txt if ((inptr = fopen(inname,"r")) == 0){ fprintf(stderr, "error opening file %s: %s", inname, strerror(inname)); return -1; } // initialization of pointer , opening of file triangleout.txt if ((outptr = fopen(outname,"w")) == 0){ fprintf(stderr, "error opening file %s: %s", outname, strerror(outname)); return -1; } int result; while(true){ result = fscanf(inptr,"%d %d %d",&a, &b, &c); if (result == eof) break; if (result < 3) // ignore incomplete lines continue; // normal stuff }
Comments
Post a Comment