Results 1 to 4 of 4
Hello all
I found this example in java2s.com
Code:
#include <stdio.h>
#include <stdlib.h>
double d[10] = {
1.3, 1.7, 1.23, 1.9, 0.97,
1.5, 7.4, 0.0, 1.01, 8.75
};
int main(void)
...
- 09-14-2008 #1Just Joined!
- Join Date
- May 2008
- Posts
- 14
Read text file with C
Hello all
I found this example in java2s.com
Seem my.txt in example is a binary file, Is possible to read number from text file , the file contain something like this "293 493 493 23 4 22 43 22"Code:#include <stdio.h> #include <stdlib.h> double d[10] = { 1.3, 1.7, 1.23, 1.9, 0.97, 1.5, 7.4, 0.0, 1.01, 8.75 }; int main(void) { int i; FILE *fp; if((fp = fopen("my.txt", "wb")) == NULL) { printf("Cannot open file.\n"); exit(1); } /* write the entire array in one step */ if( fwrite(d, sizeof d, 1, fp) != 1) { printf("Write error.\n"); exit(1); } fclose(fp); if((fp = fopen("my.txt", "rb"))==NULL) { printf("Cannot open file.\n"); exit(1); } /* clear the array */ for(i = 0; i < 10; i++) d[i] = 0.0; /* read the entire array in one step */ if(fread(d, sizeof d, 1, fp) != 1) { printf("Read error.\n"); exit(1); } fclose(fp); /* display the array */ for(i = 0; i < 10; i++) printf("%f ", d[i]); return 0; }
Thanks.
- 09-14-2008 #2
Yes its possible but you have to convert your numbers or data to character/string
and use fputc or fputs
- 09-14-2008 #3
oops got it backwards...yes its possible but you have to delimit the number(in your example you used spaces) and you have to convert the numbers(which are characters) into a valid number format...i.e int long, float, double
try info the strtol family of functions
- 09-16-2008 #4Just Joined!
- Join Date
- May 2008
- Posts
- 14
Thanks, I found a simple method by using fscanf
Code:void getArray(int a[], int size, char fileName[]){ FILE *fp; fp = fopen(fileName, "r"); //open file , read only int i = 0; //array pointer run bt 0 - (size-1) int value; //keep value at pointer position /* loop until all data keep into array */ while( (!feof(fp)) || (i < size)){ fscanf(fp, "%d", &value); a[i] = value; i++; } /* close file */ fclose(fp); }


Reply With Quote