c - read ASCII code file using fscanf -
i trying read ascii text file , write binary file. text file unlimited in size. first, tried read text file before writing it. however, maintain getting segmentation fault. don't understand may cause problem. using gdb, still cannot figure out problem. please advise.
code:# include <stdio.h> # include <stdlib.h> # include <string.h> typedef struct _filedata { int a; double b; char datastr[56]; }filedata; int main() { file * infile=fopen("output.txt", "r"); if(infile==null) { printf("error opening file"); exit(1); } filedata **input; int i=0; while( fscanf(infile,"%d %f %[^\n]s",&input[i].a,&input[i].b,&input[i].datastr)! =null) { printf("%d",input[i].a); printf("%.3f",input[i].b); printf("%[^\n]s",input[i].datastr); i++; } homecoming 0; }
my text file is 47 34.278 line of text 48 23.678 very long line 49 12.4569 short line 50 117.906 world beautiful 51 34.789 hello world!
the problem in code have pointer:
filedata** input;
you using pointer though it's not been initialized point valid memory.
since writing info out stdout
after reading file, can use:
filedata input; while( fscanf(infile,"%d %lf %55[^\n]",&input.a, &input.b, input.datastr) == 3) // notice chage here { printf("%d",input.a); printf("%.3f",input.b); printf("%s\n",input.datastr); }
but then, don't understand need struct _filedata
. can use:
int intvalue; double doublevalue; char stringvalue[56]; while( fscanf(infile,"%d %lf %55[^\n]",&intvalue, &doublevalue, stringvalue) == 3) { printf("%d %.3f %s\n",intvalue, doublevalue, stringvalue); }
c ascii fscanf
No comments:
Post a Comment