It's text in a text file. I'd use fgets() followed by sscanf(), or quite
possibly (if I didn't want to report file format errors with line
numbers) fscanf().
I have written a simple program check this. I am also using that there
will be a FULL STOP at the end of the text file.
SEE the COMMENTs in the program. below !!!
#include<stdlib.h>
#include<stdio.h>
int main() {
FILE *fp;
char buf[6]; // of size size 6 because File has integers
// in the file is only 2 bytes (<32768)
int *arr, nofcomma = 0, index = 0, intindex = 0;
char fch;
if ((fp = fopen("c:\\dummy.txt","r+b")) == NULL) {
printf("\nerror\n");
exit(0);
}
while ((fch = fgetc(fp))!= EOF) {
if (fch == ',')
nofcomma++; // count the no of integers
}
arr = (int *) malloc(nofcomma + 2); //allocate so much of memory.
rewind(fp); // set the pointer aagain to the beginning
while ((fch = fgetc(fp))!= EOF) {
if (fch > 47 && fch < 58)
buf[index++] = fch ;
else if (fch == ',' || fch == '.') {
buf[index] = '\0';
index = 0;
arr[intindex++] = atoi(buf);
}
}
for ( index = 0; index < nofcomma + 1 ;index++)
printf("\n the integer is %d\n",arr[index]);
return 0;
}
Now what this is working fine as succesfully I am able to read the integer
(data) from the Text file. (.txt) now what I want to do is that I want to
use these data which are stored into the Array (arry) to again store it
into the double format.
what simply i am doing is that i m using this concept. Below
see the below code
#include<stdlib.h>
#include<stdio.h>
int main() {
FILE *fp;
char buf[6]; // of size size 6 because File has integers
// in the file is only 2 bytes (<32768)
int *arr, nofcomma = 0, index = 0, intindex = 0;
double *arry_float;
char fch;
if ((fp = fopen("c:\\dummy.txt","r+b")) == NULL) {
printf("\nerror\n");
exit(0);
}
while ((fch = fgetc(fp))!= EOF) {
if (fch == ',')
nofcomma++; // count the no of integers
}
arr = (int *) malloc(nofcomma + 2); //allocate so much of memory.
arry_float = (double *)malloc(nofcomma + 2);
rewind(fp); // set the pointer aagain to the beginning
while ((fch = fgetc(fp))!= EOF) {
if (fch > 47 && fch < 58)
buf[index++] = fch ;
else if (fch == ',' || fch == '.') {
buf[index] = '\0';
index = 0;
arr[intindex++] = atoi(buf);
arry_float[intindex - 1] = (double) ( arr[intindex - 1] / pow (2,13));
++intindex;
}
}
for ( index = 0; index < nofcomma + 1 ;index++)
printf("\n the integer is %lf \n", arry_float[index]);
return 0;
}
Now I having the problem and geting the segmentation fault
please let me know what is the fault i am doing ??????