0

I would like to write an array of integers into a file using C. However, I get some gibberish in the file.

The code is about a function that converts a decimal number into binary then stores it into a file.

int * decToBinary(int n) //function to transform the decimal numbers to binary
{
    static int binaryNum[16]; // array to store binary number      
    int i = 0; // counter for binary array
    while (n > 0) {
        binaryNum[i] = n % 2; // storing remainder in binary array
        n = n / 2;
        i++;
    }
    return binaryNum;
}

int main()
{  
   FILE *infile;
   int i;
   int *p;
   int decimal= 2000;
   int written = 0;

   infile = fopen("myfile.txt","w");
   p = decToBinary(decimal);
   written = fwrite(p,sizeof(int),sizeof(p),infile) ;

   if (written == 0) {
       printf("Error during writing to file !");
   }
   fclose(infile);
   return 0;

}

This is what I get in my file:

This is what I get in my file:


This is what I get when I write a text as a test, it does not have any problem with the text, but it has with the array.

char str[] = "test text --------- \n";
infile = fopen("myfile.txt","wb");
p=decToBinary(decimal);
fwrite(str , 1 , sizeof(str) , infile);
written = fwrite(p,sizeof(int),sizeof(p),infile) ;

enter image description here


And this is what I get when I make this change:

written = fwrite(&p,sizeof(int),sizeof(p),infile) ;

enter image description here

9
  • 7
    fwrite writes raw binary. If you want ASCII conversion, use fprintf or similar. Commented Nov 20, 2018 at 11:48
  • Seems to me you are asking for the sizeof a pointer in written = fwrite(p,sizeof(int),sizeof(p),infile) e.g. sizeof(p) - according to the func desc. you should however use the number of elements(or omit them to write the full array). Commented Nov 20, 2018 at 11:55
  • You explicitly set size of array to 16. Why? Commented Nov 20, 2018 at 11:56
  • @Lundin Unfortunately, there's no %b format specifier (yet???), so fprintf won't help out either... Commented Nov 20, 2018 at 12:27
  • 2
    Possible duplicate of How to write an array to file in C Commented Mar 20, 2019 at 7:31

2 Answers 2

2

First, be aware that there are two interpretations for 'binary':

int n = 1012;
fwrite(&n, sizeof(n), 1, file);

This writes out the data just as is; as it is represented in form of bits, output is considered "binary" (a binary file).

Your question and the code you provided, though, rather imply that you actually want to have a file containing the numbers in binary text format, i. e. 7 being represented by string "111".

Then first, be aware that 0 and 1 do not represent the characters '0' and '1' in most, if not all, encodings. Assuming ASCII or compatible, '0' is represented by value 48, '1' by value 49. As C standard requires digits [0..9] being consecutive characters (this does not apply for any other characters!), you can safely do:

binaryNum[i] = '0' + n % 2;

Be aware that, as you want strings, you chose the bad data type, you need a character array:

static char binaryNum[X];

X??? We need to talk about required size!

If we create strings, we need to null-terminate them. So we need place for the terminating 0-character (really value 0, not 48 for character '0'), so we need at least one character more.

Currently, due to the comparison n > 0, you consider negative values as equal to 0. Do you really intend this? If so, you might consider unsigned int as data type, otherwise, leave some comment, then I'll cover handling negative values later on.

With restriction to positive values, 16 + 1 as size is fine, assuming int has 32 bit on your system! However, C standard allows int to be smaller or larger as well. If you want to be portable, use CHAR_BIT * sizeof(int) / 2 (CHAR_BIT is defined in <limits.h>; drop division by 2 if you switch to unsigned int).

There is one special case not covered: integer value 0 won't enter the loop at all, thus you'd end up with an empty string, so catch this case separately:

if(n == 0)
{
    binaryNum[i++] = '0';
}
else
{
    while (n > 0) { /.../ }
}
// now the important part:
// terminate the string!
binaryNum[i] = 0;

Now you can simply do (assuming you changed p to char*):

written = fprintf(file, "%s\n", p);
//                         ^^ only if you want to have each number on separate line
//                          you can replace with space or drop it entirely, if desired

Be aware that the algorithm, as is, prints out least significant bits first! You might want to have it inverse, then you'd either yet have to revert the string or (which I would prefer) start with writing the terminating 0 to the end and then fill up the digits one by one towards front - returning a pointer to the last digit (the most significant one) written instead of always the start of the buffer.

One word about your original version:

written = fwrite(p, sizeof(int), sizeof(p), infile);

sizeof(p) gives you the size of a pointer; this one is system dependent, but will always be the same on the same system, most likely 8 on yours (if modern 64-bit hardware), possibly 4 (on typical 32-bit CPU), other values on less common systems are possible as well. You'd need to return the number of characters printed separately (and no, sizeof(binaryNum) won't be suitable as it always returns 17, assuming 32-bit int and all changes shown above applied).

Sign up to request clarification or add additional context in comments.

3 Comments

1) yes, I want "want to have a file containing the numbers in binary text format" 2) I don't want to consider the negative values.
CHAR_BIT defines the number of bits in a byte (source: [link] (tutorialspoint.com/c_standard_library/limits_h.htm) ), however, the integers that I would like to convert into binary text format can go upto 2 bytes.
@Lavender CHAR_BIT * sizeof(unsigned int) -> 8*4 -> 32 (for unsigned) or devide by 2 for signed - as in the answer...
0

You probably want this:

...
int main()
{
  int decimal = 2000;    
  int *p = decToBinary(decimal);

  for (int i = 0; i< 16; i++)
  {
    printf("%d", p[i]);
  }

  return 0;
}

The output goes to the terminal instead into a file.

For writing into a file use fopen as in your code, and use fprintf instead of printf.

Concerning the decToBinary there is still room for improvement, especially you could transform the number directly into an array of char containing only chars 0 and 1 using the << and & operators.

2 Comments

thank you for the insight about the decRoBinary, do you mean something like this: c4learn.com/c-programs/decimal-to-binary-using-bitwise-and.html ?
@Lavender yes exactly

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.