0

I know that you can do this if you have elements in your array:

FILE *ptr;
ptr = fopen( bobby.txt , "wb" );
int array[3] = {1,2,3};
fwrite(array, sizeof(int), 3, ptr );
fclose(ptr);

but, when we come across corner cases like an empty array, how would we copy an empty array into a file? Would it look something like this?

FILE *ptr;
ptr = fopen( bobby.txt , "wb" );
int array[0] = {};
fwrite(array, sizeof(int), 0, ptr );
fclose(ptr);

EDIT:

if the array was null would that also count as an empty array?

TakShing
  • 145
  • 1
  • 2
  • 12
  • If your array is empty don't write it to your file. And don't read it from your file. This assumes that something else will tell you the length of the array when you read it. – JS1 Nov 24 '14 at 05:49
  • One last thing, is possible to check in my code if the file that I am writing to exists or do I have to know beforehand whether or not it exists already? – TakShing Nov 24 '14 at 05:54
  • 1
    @TakShing The documentation for [**`fopen()`**](http://en.cppreference.com/w/c/io/fopen) will likely help you understand what to expect when the call *fails* to open the named file. – WhozCraig Nov 24 '14 at 06:21
  • Try `access()` or `stat()`. – JS1 Nov 24 '14 at 06:25
  • Why don't you add an 'if' statement before writing it? If the array is empty or NULL you simply write a newline char '\n' so that when you will read again the file you will know it represents the empty array. – Emisilve86 Nov 24 '14 at 09:24

1 Answers1

2

fopen( bobby.txt , "wb" );

This is wrong.

fopen( "bobby.txt" , "wb" );

The array has nothing in it and your are trying to copy nothing to a file? This sounds contradictory. When there is nothing in the array don't write it to a file.

If you want to check whether the file exists or not check the below link.

What's the best way to check if a file exists in C? (cross platform)

Community
  • 1
  • 1
Gopi
  • 19,784
  • 4
  • 24
  • 36