By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
424,963 Members | 1,784 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 424,963 IT Pros & Developers. It's quick & easy.

Output Array to a new file

P: 6
I have a function that will read a file of numbers and place them into an array. I need to create a new function that will, given that stored array, output the array to a new file.

This is the code I have:

Expand|Select|Wrap|Line Numbers
  1.  
  2. int Save(char *File, long *Array, int Size) {
  3.   FILE *fp = fopen(File, "wb");
  4.   if (fp == NULL) { // check to see if file opens; if NULL, failed
  5.     printf("Error opening file. \n");
  6.     return 0;
  7.   }
  8.  
  9.   if (fwrite(&Array, sizeof(int), 1, fp) != Size) {
  10.     printf("File write error.");
  11.   }
  12.  
  13.   fclose(fp);
  14.   return (Size);
  15. }
  16.  
Right now, it does not work. The fwrite function is suppose to return the number of copies (= Size, determined in other function -- that does work), but it is not copying all of the values. I'm unsure of how to do it.
Sep 26 '10 #1

✓ answered by Banfa

Well you probably should use Array rather than &Array but that wont make much difference.

You see that data because you are writing binary data to the file, the contents of the integers, so the data in the file is binary and non-readable.

If you want the file to be readable then use fprintf instead of fwrite.

Share this Question
Share on Google+
4 Replies


Banfa
Expert Mod 5K+
P: 8,916
But you have passed 1 as the number of records to write (effectively the array size for your code) to fwrite.
Sep 26 '10 #2

P: 6
Haha, wow, you are right. I didn't even see that. After changing that line to

Expand|Select|Wrap|Line Numbers
  1.    if (fwrite(&Array, sizeof(int), Size, fp) != Size) {
  2.  
It now runs properly. However, when I check the output file, this is what is written:

^B^Z\210^B^WF3^C%?Houtputt

I believe it's because in my fwrite line, I am using &Array rather than the value -- however, I don't know how I can retrieve the values from Array and print them.
Sep 26 '10 #3

Banfa
Expert Mod 5K+
P: 8,916
Well you probably should use Array rather than &Array but that wont make much difference.

You see that data because you are writing binary data to the file, the contents of the integers, so the data in the file is binary and non-readable.

If you want the file to be readable then use fprintf instead of fwrite.
Sep 26 '10 #4

P: 6
That ended up working. I changed the fwrite to
Expand|Select|Wrap|Line Numbers
  1.   for (count = 0; count < Size; count++) {
  2.     fprintf(fp, "%ld\n", Array[count]);
  3.   }
  4.  
and now it saves it perfectly. Thank you!
Sep 26 '10 #5

Post your reply

Sign in to post your reply or Sign up for a free account.