I would like to write a [250]x[250] array in a file.
*note that you say this but your demonstration code uses an array of size
[50][2] so that's what I've used.
If the file will be written and read back on the same machine (ie you
don't need to worry about portability), and it doesn't need to be humanly
readable, you can open the file in binary mode and read/write the whole
array as it is represented in memory to the file in one operation. In this
case use "wb" rather than "w".
if (! fwrite(array, sizeof(array), 1, file1)) {
perror("fwrite");
exit(EXIT_FAILURE);
}
Then to get back the data, you can declare:
double (*arrayp)[2] = malloc(sizeof(*arrayp) * 50);
if (!arrayp) {
perror("malloc");
exit(EXIT_FAILURE);
}
Open the file in "rb" mode, and use:
if (! fread(arrayp, sizeof(*arrayp) * 50, 1, file1)) {
perror("fread");
exit(EXIT_FAILURE);
}
Then to access elements use arrayp[x][y] as usual.
If the array has a small numbers of columns I know I can use a loop like:
int i,j;
double array[50][2];
FILE *file1;
file1=fopen("data.dat","w");
You should check for fopen returning an error.
for(i=0;i<50;i++){
fprintf(file1,"%f %f\ %f %f \n",array[0],array[1]);
}
This fprintf statement has a few problems: firstly you have 4 %f's and
only two double arguments. The "\ " doesn't seem to serve any purpose.
Also you aren't checking for fprintf returning an error.
Finally you may or may not want to limit the number of digits being
printed if it is for human reading and precision is not an issue. In this
case use %10.4f or something like it, where the 10 is the maximum total
number of digits and the 4 is the maximum number of digits after the
decimal point.
If you simply want to print the array to the file in a portable, humanly
readable format, then this double loop may serve your needs. The only
minor annoyance is that there will be a trailing space at the end of each
line, but you can eliminate that with a little extra code.
for (i = 0; i < 50; i++) {
for (j = 0; j < 2; j++) {
if (fprintf(file1, "%f ", array[j]) < 0) {
perror("fprintf");
exit(EXIT_FAILURE);
}
}
if (fprintf(file1, "\n") < 0) {
perror("fprintf");
exit(EXIT_FAILURE);
}
}
You can read this file back into an array but I won't post code for that
since it's a little more involved and you haven't said that you need to do
that anyway.
Again, check for fclose returning an error.
but in a case a 250 (for example) columns???? I guess there is another
way than writing 250 times array[][]???
I did it in fortran
open(unit=1,file='tab4')
do 102 k=1,2*nrow+1
write(unit=1,fmt=200)(Y(k,i),i=1,ncol)
102 continue
200 format(2X,200F10.4)
close(1)
If I understood Fortran I would know better what you are trying to
achieve; but it looks to me like this will produce a humanly readable
file. Anyhow that gives you two options.