fwrite + fread problem 
Author Message
 fwrite + fread problem

I'm having a problem with in saving and then retrieving an entire array
with fwrite and fread. Is there a way to do this without using a for
loop to save each array element one at a time? In the example below I am
using an array of integers, but this also happens when I try to use an
array of floats. Any help would be appreciated.

#include <stdio.h>
#include <stdlib.h>
#include <conio.h>

#define TOTAL 300

main()
{

        int random[TOTAL];
        int a;

        for(a=0;a<TOTAL;a++)
        {
                random[a]=rand();
        }

printf("Disply values before saving");
         for(a=0;a<TOTAL;a++)
         {
                printf("\n random[%d]=",a);
                printf("%d", random[a]);
         }

         FILE *fp;
         printf("SAVING DATA TO FILE...");
         if((fp=fopen("random.dat","w+"))==0){
                                printf("cannot open file\n");
                                exit(0);
         }

         fwrite(&random, sizeof(random), 1, fp);
         fclose(fp); /* close file */

        printf("Clear all values");
        for(a=0;a<TOTAL;a++)
        {
                        random[a]=0;
        }

         printf("RETRIEVING DATA FILE...");
         if((fp=fopen("random.dat","r"))==0){
                                printf("cannot open file\n");
                                exit(0);
         }

         fread(&random, sizeof(random), 1, fp);
         fclose(fp);

         // Now display values
         int x=0;

         for(a=0;a<TOTAL;a++)
        {
                printf("\n random[%d]=",a);
                printf("%d", random[a]);
                x++;

                if(x==20){
                        printf("Press any key to continue, CTRL-C to quit.");
                                getch();
                                x=0;}
         }

Quote:
}



Thu, 01 Feb 2001 03:00:00 GMT  
 fwrite + fread problem

   I'm having a problem with in saving and then retrieving an entire array
   with fwrite and fread. Is there a way to do this without using a for
   loop to save each array element one at a time? In the example below I am
   using an array of integers, but this also happens when I try to use an
   array of floats. Any help would be appreciated.

   #include <stdio.h>
   #include <stdlib.h>
   #include <conio.h>

Not a Standard C header file.

   #define TOTAL 300

   main()

You should specify an int return value explicitly.

   {

           int random[TOTAL];
           int a;

           for(a=0;a<TOTAL;a++)
           {
                   random[a]=rand();
           }

   printf("Disply values before saving");
            for(a=0;a<TOTAL;a++)
            {
                   printf("\n random[%d]=",a);
                   printf("%d", random[a]);
            }

            FILE *fp;

You can't declare a variable in the middle of a block.

            printf("SAVING DATA TO FILE...");
            if((fp=fopen("random.dat","w+"))==0){

You should probably use binary mode.  And there's no need for the +.

                                   printf("cannot open file\n");
                                   exit(0);
            }

            fwrite(&random, sizeof(random), 1, fp);
            fclose(fp); /* close file */

           printf("Clear all values");
           for(a=0;a<TOTAL;a++)
           {
                           random[a]=0;
           }

            printf("RETRIEVING DATA FILE...");
            if((fp=fopen("random.dat","r"))==0){
                                   printf("cannot open file\n");
                                   exit(0);
            }

            fread(&random, sizeof(random), 1, fp);
            fclose(fp);

            // Now display values

Illegal text.  You should probably comment it out.

            int x=0;

You can't declare a variable in the middle of a block.

            for(a=0;a<TOTAL;a++)
           {
                   printf("\n random[%d]=",a);
                   printf("%d", random[a]);
                   x++;

                   if(x==20){
                           printf("Press any key to continue, CTRL-C to quit.");
                                   getch();

Not a Standard C function.
                                   x=0;}
            }

   }

BTW don't post C++ to comp.lang.c.
--
(supporter of the campaign for grumpiness where grumpiness is due in c.l.c)

Please: do not email me copies of your posts to comp.lang.c
        do not ask me C questions via email; post them instead



Thu, 01 Feb 2001 03:00:00 GMT  
 fwrite + fread problem

Quote:


>   I'm having a problem with in saving and then retrieving an entire array
>   with fwrite and fread. Is there a way to do this without using a for
>   loop to save each array element one at a time? In the example below I am
>   using an array of integers, but this also happens when I try to use an
>   array of floats. Any help would be appreciated.

Well, Ben, you've done a good job of criticising every aspect of his program
that does not conform to The Standard, but if you had read his question a
little more carefully, you would have seen he was asking for help on writing
an entire array without using a for loop.

You can write the entire array either using a for loop, as you'd probably
guessed:

for(i=0;i<TOTAL;i++) {
    fwrite(&array[i],sizeof(array[i]),1,fp);

Quote:
}

or write it all at once, changing the number 1 to the number of elements you
want to write:

fwrite(&array[0],sizeof(array[0]),TOTAL,fp);

(Your slightly modified program below)
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>

#define TOTAL 5

void main(void)
{
    int rnd[TOTAL],a; // I find a variable and function with the same name
confusing, so random[] is now rnd[]
    FILE *fp; // best to put all your declarations at the top

    for(a=0;a<TOTAL;a++) {
        rnd[a]=rand();
    }

    printf("Displaying values...\n");
    for(a=0;a<TOTAL;a++) {
        printf(" rnd[%d] = %d\n",a,rnd[a]); // printf can have more than one
argument
    }

    printf("Saving to file...\n");
    if((fp=fopen("random.dat","wb"))==NULL) {
        printf("Error opening file\n");
        exit(1); // error - so we should really exit with non zero return
code
    }

    // rnd is an array, hence &rnd[0] or just rnd will point to first
element
    fwrite(rnd,sizeof(rnd[0]),TOTAL,fp);
    fclose(fp);

    printf("Clearing all values...\n");
    for(a=0;a<TOTAL;a++) {
        rnd[a]=0;
    }

    printf("Retreiving from file...\n");
    if((fp=fopen("random.dat","rb"))==NULL) {
        printf("Error opening file\n");
        exit(1);
    }

    fread(rnd,sizeof(rnd[0]),TOTAL,fp);
    fclose(fp);

    printf("Displaying values...\n");
    for(a=0;a<TOTAL;a++) {
        printf(" rnd[%d] = %d\n",a,rnd[a]);
    }

Quote:
}


The Network Games Site - http://freespace.{*filter*}.net/jonathan.carter
PGP 5.0 public key available on request


Thu, 01 Feb 2001 03:00:00 GMT  
 fwrite + fread problem



   >
   >   I'm having a problem with in saving and then retrieving an entire array
   >   with fwrite and fread. Is there a way to do this without using a for
   >   loop to save each array element one at a time? In the example below I am
   >   using an array of integers, but this also happens when I try to use an
   >   array of floats. Any help would be appreciated.

   Well, Ben, you've done a good job of criticising every aspect of his program
   that does not conform to The Standard, but if you had read his question a
   little more carefully, you would have seen he was asking for help on writing
   an entire array without using a for loop.

He *did* write the entire array without a for loop.  So how does his
question make sense?
--
(supporter of the campaign for grumpiness where grumpiness is due in c.l.c)

Please: do not email me copies of your posts to comp.lang.c
        do not ask me C questions via email; post them instead



Thu, 01 Feb 2001 03:00:00 GMT  
 fwrite + fread problem

Quote:

> #include <stdio.h>
> #include <stdlib.h>
> #include <conio.h>

This header is still non-standard.  Please don't recommend it here without
at least pointing out that fact.

Quote:
> #define TOTAL 5

> void main(void)

Nasal demons.  main returns int.

Quote:
> {
>     int rnd[TOTAL],a; // I find a variable and function with the same name
> confusing, so random[] is now rnd[]

//-comments are not (yet) legal C.  Moreover, allowing one to run over a
line break (as you've done here) will almost certainly cause syntax errors
even in implementations that allow // as an extension.

And there's no standard C function whose name is `random', by the way.

Quote:
>     FILE *fp; // best to put all your declarations at the top

No, it's required, as Ben pointed out.

Quote:
>     for(a=0;a<TOTAL;a++) {
>         rnd[a]=rand();
>     }

>     printf("Displaying values...\n");
>     for(a=0;a<TOTAL;a++) {
>         printf(" rnd[%d] = %d\n",a,rnd[a]); // printf can have more than one
> argument
>     }

>     printf("Saving to file...\n");
>     if((fp=fopen("random.dat","wb"))==NULL) {
>         printf("Error opening file\n");
>         exit(1); // error - so we should really exit with non zero return
> code

More to the point, you should call exit with the argument EXIT_FAILURE,
defined in <stdlib.h>.  Using a literal 1 causes implementation-defined
behaviour.

Quote:
>     }

>     // rnd is an array, hence &rnd[0] or just rnd will point to first
> element
>     fwrite(rnd,sizeof(rnd[0]),TOTAL,fp);
>     fclose(fp);

>     printf("Clearing all values...\n");
>     for(a=0;a<TOTAL;a++) {
>         rnd[a]=0;
>     }

>     printf("Retreiving from file...\n");
>     if((fp=fopen("random.dat","rb"))==NULL) {
>         printf("Error opening file\n");
>         exit(1);
>     }

>     fread(rnd,sizeof(rnd[0]),TOTAL,fp);
>     fclose(fp);

>     printf("Displaying values...\n");
>     for(a=0;a<TOTAL;a++) {
>         printf(" rnd[%d] = %d\n",a,rnd[a]);
>     }

You need a return value for main() here when you change it to be int-valued.

Quote:
> }

--



Thu, 01 Feb 2001 03:00:00 GMT  
 fwrite + fread problem

Quote:




>   >   I'm having a problem with in saving and then retrieving an entire
array
>   >   with fwrite and fread. Is there a way to do this without using a for
>   >   loop to save each array element one at a time? In the example below
I am
>   >   using an array of integers, but this also happens when I try to use
an
>   >   array of floats. Any help would be appreciated.

>   Well, Ben, you've done a good job of criticising every aspect of his
program
>   that does not conform to The Standard, but if you had read his question
a
>   little more carefully, you would have seen he was asking for help on
writing
>   an entire array without using a for loop.

>He *did* write the entire array without a for loop.  So how does his
>question make sense?

His line: fread(&random, sizeof(random), 1, fp);
would not work because he was passing a pointer to a pointer - just:
fread(random, sizeof(random), 1, fp); or fread(&random[0], sizeof(random),
1, fp); would have done since random was an array.


The Network Games Site - http://freespace.{*filter*}.net/jonathan.carter
PGP 5.0 public key available on request



Fri, 02 Feb 2001 03:00:00 GMT  
 fwrite + fread problem
My original question may be unclear. The problem is, after I save the
array, only the first 500 bytes or 250 array elements are read back into
the array after it was reinitialized with zeroes. I have tried it with
or without the ampersand (as someone suggested) in front of the array
and I get the same result. Is there a maximum size of array that fwrite
can use in only one pass?  

George



Fri, 02 Feb 2001 03:00:00 GMT  
 fwrite + fread problem

Quote:

>My original question may be unclear. The problem is, after I save the
>array, only the first 500 bytes or 250 array elements are read back into
>the array after it was reinitialized with zeroes. I have tried it with
>or without the ampersand (as someone suggested) in front of the array
>and I get the same result.

A couple of people noted that you didn't ope the file in binary mode.
Did you fix that (i.e. use "wb" instead of "w" and "rb" instead of "r")?

Quote:
>Is there a maximum size of array that fwrite
>can use in only one pass?  

It should be able to cope with any array you can create using standard
mechanisms.

--
-----------------------------------------


-----------------------------------------



Fri, 02 Feb 2001 03:00:00 GMT  
 fwrite + fread problem


...

Quote:
>>He *did* write the entire array without a for loop.  So how does his
>>question make sense?

>His line: fread(&random, sizeof(random), 1, fp);
>would not work because he was passing a pointer to a pointer - just:

random is defined in the code as an array. &random produces the address
of the array which is fine.

Quote:
>fread(random, sizeof(random), 1, fp); or fread(&random[0], sizeof(random),
>1, fp); would have done since random was an array.

Yes, that would work too.

--
-----------------------------------------


-----------------------------------------



Fri, 02 Feb 2001 03:00:00 GMT  
 fwrite + fread problem

Quote:

>My original question may be unclear. The problem is, after I save the
>array, only the first 500 bytes or 250 array elements are read back into
>the array after it was reinitialized with zeroes. I have tried it with
>or without the ampersand (as someone suggested) in front of the array
>and I get the same result. Is there a maximum size of array that fwrite
>can use in only one pass?

>George

You could try using fwrite(random,sizeof(random[0]),TOTAL,fp) and check the
return code from it - it should return the number of int's it wrote. If it's
!= TOTAL, then for some reason they're not all being written to disk. Same
with reading, check the return code against TOTAL.


The Network Games Site - http://freespace.{*filter*}.net/jonathan.carter
PGP 5.0 public key available on request



Fri, 02 Feb 2001 03:00:00 GMT  
 fwrite + fread problem

Quote:



>...

>>>He *did* write the entire array without a for loop.  So how does his
>>>question make sense?

>>His line: fread(&random, sizeof(random), 1, fp);
>>would not work because he was passing a pointer to a pointer - just:

>random is defined in the code as an array. &random produces the address
>of the array which is fine.

You're right about &random and just random being identical - something I've
never noticed before! In that case, George, ignore what I've been saying...


The Network Games Site - http://freespace.{*filter*}.net/jonathan.carter
PGP 5.0 public key available on request



Fri, 02 Feb 2001 03:00:00 GMT  
 fwrite + fread problem
Jonathan Carter wrote to Lawrence Kirby:

Quote:

> You're right about &random and just random being identical - something I've
> never noticed before! In that case, George, ignore what I've been saying...

No, they're not equivalent, but similar.  &array has the type, "type (*)
[SIZE]", while array decays to &array [0], which has the type, "type *".

&array refers to the entire array, so pointer arithmetic on it will
increment the pointer by units of sizeof (array).  Pointer arithmetic on
&array [0] will increment the pointer by units of sizeof (array [0]).

However both &array [0] and &array point to the same location in memory
(apparent if, say, you converted them to type unsigned char *).  So
they're not identical, but they are very closely related.

--

I believe we can change anything.
I believe in my dream.
    - Joe Satriani



Fri, 02 Feb 2001 03:00:00 GMT  
 fwrite + fread problem

<snip context which declares `random' as an array>

Quote:
> You're right about &random and just random being identical - something I've
> never noticed before! In that case, George, ignore what I've been saying...

They're not really identical.  They can be meaningfully converted to
pointers which compare equal, but they certainly have different types.

--



Fri, 02 Feb 2001 03:00:00 GMT  
 fwrite + fread problem

   His line: fread(&random, sizeof(random), 1, fp);
   would not work because he was passing a pointer to a pointer - just:
   fread(random, sizeof(random), 1, fp); or fread(&random[0], sizeof(random),
   1, fp); would have done since random was an array.

Not true.  Did you *test* his code?
--
(supporter of the campaign for grumpiness where grumpiness is due in c.l.c)

Please: do not email me copies of your posts to comp.lang.c
        do not ask me C questions via email; post them instead



Fri, 02 Feb 2001 03:00:00 GMT  
 fwrite + fread problem

Quote:

> I'm having a problem with in saving and then retrieving an entire array
> with fwrite and fread. Is there a way to do this without using a for
> loop to save each array element one at a time? In the example below I am
> using an array of integers, but this also happens when I try to use an
> array of floats. Any help would be appreciated.

> After tinkering a bit I solved my problem. In my oroginal code I opened the file for writing in "w+" mode and for reading in "r" mode. I changed these to "w+b" and "r+b" modes respectively and now it saves and retrieves the entire array. But I'm still stumped why in my original code the first 500 bytes were still saved and retrieved correctly when I had made such an error? Stuff like this makes me rip hair out of my head. Thanks for the suggestions, everybody.

George


Fri, 02 Feb 2001 03:00:00 GMT  
 
 [ 18 post ]  Go to page: [1] [2]

 Relevant Pages 

1. problem with fwrite / fread

2. Problem with struct/array inside a struct using fread/fwrite

3. microsoft endian problem with fread/fwrite

4. fread/fwrite problem

5. problem with fread/fwrite

6. fread()/fseek()/fwrite() problem?

7. fread, fwrite probs

8. Please Help (fread, fwrite)

9. fwrite(), fread() portability.

10. fopen() fseek() fread() fwrite()

11. Strange byte order using fread() and fwrite()

12. fread and fwrite

 

 
Powered by phpBB® Forum Software