Thread: simple fread doesn't work

  1. #1
    Registered User
    Join Date
    Jun 2004
    Posts
    123

    simple fread doesn't work

    Hi,
    just started to learn working with files. Trying to run this code, which writes array to a file & then copy it another array and display it on screen:
    Code:
    #include<stdio.h>
    #include<stdlib.h>
    
    #define SIZE 20
    int main()
    {
    	int count , array1[SIZE], array2[SIZE];
    	FILE *fp;
    	for (count=0; count<SIZE;count++)
    		array1[count]=2*count;
    	if ((fp=fopen("direct.txt", "wb"))==NULL)
    	{
    		fprintf(stderr, "eror opening file (1)");
    		exit(1);
    	}
    
    	if (fwrite (array1, sizeof (int), SIZE, fp)!=SIZE)
    	{
    		fprintf(stderr, "error writing to file");
    		exit(1);
    	}
    	fclose  (fp);
    	if ((fp=fopen("direct.txt", "rb"))==NULL)
    	{
    		fprintf (stderr, "error opening file (2)");
    		exit(1);
    	}  
    	if (fread (array2, sizeof(int), SIZE, fp)!=SIZE);
    	{
    		fprintf(stderr, "error reading file! \n");
    		exit(1);
    	}
    	fclose (fp);
    	for (count=0; count<SIZE;count++)
    	printf ("%d\t%d\n", array1[count], array2[count]);
    	return (0);
    }
    ...and the error:
    error reading file!
    which means all program runs OK, till the point where it should read data from binary file. Where was I wrong?

  2. #2
    Registered User
    Join Date
    Aug 2001
    Posts
    247
    Code:
    if (fread (array2, sizeof(int), SIZE, fp)!=SIZE);
    get rid of the semi-colon at the end of the conditional if statement...
    hoping to be certified (programming in c)
    here's the news - I'm officially certified.

  3. #3
    Registered User
    Join Date
    Aug 2001
    Posts
    247
    Also array2 is a pointer to the address to the first element of the array. You may have to loop through array2, reading the file one int value at a time.
    hoping to be certified (programming in c)
    here's the news - I'm officially certified.

  4. #4
    Registered User
    Join Date
    Jun 2004
    Posts
    123
    OK, it works fine. Thanks!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. why fread does not work?
    By nanxy in forum C Programming
    Replies: 4
    Last Post: 07-29-2008, 11:17 PM
  2. Why the simple Socket Snippet doesn't work?
    By meili100 in forum Networking/Device Communication
    Replies: 2
    Last Post: 05-05-2008, 04:57 AM
  3. A simple return and it does not work
    By kotte in forum C++ Programming
    Replies: 4
    Last Post: 01-27-2006, 12:22 AM
  4. Simple C++ Won't Work...
    By jothesmo in forum C++ Programming
    Replies: 10
    Last Post: 11-25-2005, 07:00 PM
  5. Novice Beginner: Simple hello world wont work
    By hern in forum C++ Programming
    Replies: 8
    Last Post: 06-25-2005, 12:16 PM