Quick Q - Array to File

This is a discussion on Quick Q - Array to File within the C Programming forums, part of the General Programming Boards category; I'm sure there is likely a simple solution to this, but my brain has turned to mush working on this ...

  1. #1
    Registered User
    Join Date
    Mar 2003
    Posts
    25

    Quick Q - Array to File

    I'm sure there is likely a simple solution to this, but my brain has turned to mush working on this code.

    Code:
    	while(i > 0)
    	{
    	   printf("%d\n", array[--i]);
    	}
    if this code will simply display my array....How can I change this to write the array[--i] to a file. I've tried the following code, but get an error message. Could someone please point me in the right direction.

    Code:
    	while(i > 0)
    	{
    	   fptr = fopen("junk3.txt", "w");
    	   fwrite(array[--i], sizeof(array[i]), 1, fptr);
    	   fclose(fptr);
    	}

  2. #2
    ggs
    ggs is offline
    C > C++ duders ggs's Avatar
    Join Date
    Aug 2001
    Posts
    435
    Code:
    fwrite(&array[--i], ... /* why not write entire array at once? */
    fwrite(array, i, 1, ... /* hooray */
    .sect signature

  3. #3
    Registered User
    Join Date
    Mar 2003
    Location
    UK
    Posts
    169
    Put fclose() outside the while loop.

  4. #4
    ggs
    ggs is offline
    C > C++ duders ggs's Avatar
    Join Date
    Aug 2001
    Posts
    435
    seppaku
    .sect signature

  5. #5
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,006
    Here is another idea.
    Code:
    fptr = fopen("junk3.txt", "w");
    if(fptr)
    {
       while(i > 0)
       {
          fprintf(fptr, "%d\n", array[--i]);
       }
       fclose(fptr);
    }
    Text files have advantages of being "human readable", the data can be viewed/changed easily using a text editor, and they are fairly portable.
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. opening empty file causes access violation
    By trevordunstan in forum C Programming
    Replies: 10
    Last Post: 10-21-2008, 11:19 PM
  2. Formatting the contents of a text file
    By dagorsul in forum C++ Programming
    Replies: 2
    Last Post: 04-29-2008, 12:36 PM
  3. Post...
    By maxorator in forum C++ Programming
    Replies: 12
    Last Post: 10-11-2005, 08:39 AM
  4. Dikumud
    By maxorator in forum C++ Programming
    Replies: 1
    Last Post: 10-01-2005, 06:39 AM
  5. Unknown Memory Leak in Init() Function
    By CodeHacker in forum Windows Programming
    Replies: 3
    Last Post: 07-09-2004, 09:54 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21