Writing an array of integers into a file using C











up vote
-1
down vote

favorite












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










share|improve this question




















  • 6




    fwrite writes raw binary. If you want ASCII conversion, use fprintf or similar.
    – Lundin
    Nov 20 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).
    – ats
    Nov 20 at 11:55












  • You explicitly set size of array to 16. Why?
    – purec
    Nov 20 at 11:56










  • @Lundin Unfortunately, there's no %b format specifier (yet???), so fprintf won't help out either...
    – Aconcagua
    Nov 20 at 12:27










  • @purec Obviously because of 32-bit int and not caring for negative values. Unfortunately, 0 isn't covered appropriately either.
    – Aconcagua
    Nov 20 at 12:29















up vote
-1
down vote

favorite












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










share|improve this question




















  • 6




    fwrite writes raw binary. If you want ASCII conversion, use fprintf or similar.
    – Lundin
    Nov 20 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).
    – ats
    Nov 20 at 11:55












  • You explicitly set size of array to 16. Why?
    – purec
    Nov 20 at 11:56










  • @Lundin Unfortunately, there's no %b format specifier (yet???), so fprintf won't help out either...
    – Aconcagua
    Nov 20 at 12:27










  • @purec Obviously because of 32-bit int and not caring for negative values. Unfortunately, 0 isn't covered appropriately either.
    – Aconcagua
    Nov 20 at 12:29













up vote
-1
down vote

favorite









up vote
-1
down vote

favorite











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










share|improve this question















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







c arrays file integer storage






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 20 at 12:51









Mike

1,9471521




1,9471521










asked Nov 20 at 11:44









Lavender

1214




1214








  • 6




    fwrite writes raw binary. If you want ASCII conversion, use fprintf or similar.
    – Lundin
    Nov 20 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).
    – ats
    Nov 20 at 11:55












  • You explicitly set size of array to 16. Why?
    – purec
    Nov 20 at 11:56










  • @Lundin Unfortunately, there's no %b format specifier (yet???), so fprintf won't help out either...
    – Aconcagua
    Nov 20 at 12:27










  • @purec Obviously because of 32-bit int and not caring for negative values. Unfortunately, 0 isn't covered appropriately either.
    – Aconcagua
    Nov 20 at 12:29














  • 6




    fwrite writes raw binary. If you want ASCII conversion, use fprintf or similar.
    – Lundin
    Nov 20 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).
    – ats
    Nov 20 at 11:55












  • You explicitly set size of array to 16. Why?
    – purec
    Nov 20 at 11:56










  • @Lundin Unfortunately, there's no %b format specifier (yet???), so fprintf won't help out either...
    – Aconcagua
    Nov 20 at 12:27










  • @purec Obviously because of 32-bit int and not caring for negative values. Unfortunately, 0 isn't covered appropriately either.
    – Aconcagua
    Nov 20 at 12:29








6




6




fwrite writes raw binary. If you want ASCII conversion, use fprintf or similar.
– Lundin
Nov 20 at 11:48




fwrite writes raw binary. If you want ASCII conversion, use fprintf or similar.
– Lundin
Nov 20 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).
– ats
Nov 20 at 11:55






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).
– ats
Nov 20 at 11:55














You explicitly set size of array to 16. Why?
– purec
Nov 20 at 11:56




You explicitly set size of array to 16. Why?
– purec
Nov 20 at 11:56












@Lundin Unfortunately, there's no %b format specifier (yet???), so fprintf won't help out either...
– Aconcagua
Nov 20 at 12:27




@Lundin Unfortunately, there's no %b format specifier (yet???), so fprintf won't help out either...
– Aconcagua
Nov 20 at 12:27












@purec Obviously because of 32-bit int and not caring for negative values. Unfortunately, 0 isn't covered appropriately either.
– Aconcagua
Nov 20 at 12:29




@purec Obviously because of 32-bit int and not caring for negative values. Unfortunately, 0 isn't covered appropriately either.
– Aconcagua
Nov 20 at 12:29












2 Answers
2






active

oldest

votes

















up vote
1
down vote













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, "%sn", 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).






share|improve this answer























  • 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.
    – Lavender
    Nov 20 at 12:43










  • 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
    Nov 20 at 13:03










  • @Lavender CHAR_BIT * sizeof(unsigned int) -> 8*4 -> 32 (for unsigned) or devide by 2 for signed - as in the answer...
    – Aconcagua
    Nov 20 at 15:39




















up vote
0
down vote













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.






share|improve this answer





















  • 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
    Nov 21 at 11:19










  • @Lavender yes exactly
    – Jabberwocky
    Nov 21 at 12:21











Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53392304%2fwriting-an-array-of-integers-into-a-file-using-c%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























2 Answers
2






active

oldest

votes








2 Answers
2






active

oldest

votes









active

oldest

votes






active

oldest

votes








up vote
1
down vote













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, "%sn", 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).






share|improve this answer























  • 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.
    – Lavender
    Nov 20 at 12:43










  • 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
    Nov 20 at 13:03










  • @Lavender CHAR_BIT * sizeof(unsigned int) -> 8*4 -> 32 (for unsigned) or devide by 2 for signed - as in the answer...
    – Aconcagua
    Nov 20 at 15:39

















up vote
1
down vote













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, "%sn", 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).






share|improve this answer























  • 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.
    – Lavender
    Nov 20 at 12:43










  • 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
    Nov 20 at 13:03










  • @Lavender CHAR_BIT * sizeof(unsigned int) -> 8*4 -> 32 (for unsigned) or devide by 2 for signed - as in the answer...
    – Aconcagua
    Nov 20 at 15:39















up vote
1
down vote










up vote
1
down vote









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, "%sn", 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).






share|improve this answer














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, "%sn", 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).







share|improve this answer














share|improve this answer



share|improve this answer








edited Nov 20 at 12:33

























answered Nov 20 at 12:16









Aconcagua

11.5k32142




11.5k32142












  • 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.
    – Lavender
    Nov 20 at 12:43










  • 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
    Nov 20 at 13:03










  • @Lavender CHAR_BIT * sizeof(unsigned int) -> 8*4 -> 32 (for unsigned) or devide by 2 for signed - as in the answer...
    – Aconcagua
    Nov 20 at 15:39




















  • 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.
    – Lavender
    Nov 20 at 12:43










  • 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
    Nov 20 at 13:03










  • @Lavender CHAR_BIT * sizeof(unsigned int) -> 8*4 -> 32 (for unsigned) or devide by 2 for signed - as in the answer...
    – Aconcagua
    Nov 20 at 15:39


















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.
– Lavender
Nov 20 at 12:43




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.
– Lavender
Nov 20 at 12:43












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
Nov 20 at 13:03




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
Nov 20 at 13:03












@Lavender CHAR_BIT * sizeof(unsigned int) -> 8*4 -> 32 (for unsigned) or devide by 2 for signed - as in the answer...
– Aconcagua
Nov 20 at 15:39






@Lavender CHAR_BIT * sizeof(unsigned int) -> 8*4 -> 32 (for unsigned) or devide by 2 for signed - as in the answer...
– Aconcagua
Nov 20 at 15:39














up vote
0
down vote













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.






share|improve this answer





















  • 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
    Nov 21 at 11:19










  • @Lavender yes exactly
    – Jabberwocky
    Nov 21 at 12:21















up vote
0
down vote













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.






share|improve this answer





















  • 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
    Nov 21 at 11:19










  • @Lavender yes exactly
    – Jabberwocky
    Nov 21 at 12:21













up vote
0
down vote










up vote
0
down vote









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.






share|improve this answer












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.







share|improve this answer












share|improve this answer



share|improve this answer










answered Nov 20 at 13:08









Jabberwocky

26.4k93769




26.4k93769












  • 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
    Nov 21 at 11:19










  • @Lavender yes exactly
    – Jabberwocky
    Nov 21 at 12:21


















  • 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
    Nov 21 at 11:19










  • @Lavender yes exactly
    – Jabberwocky
    Nov 21 at 12:21
















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
Nov 21 at 11:19




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
Nov 21 at 11:19












@Lavender yes exactly
– Jabberwocky
Nov 21 at 12:21




@Lavender yes exactly
– Jabberwocky
Nov 21 at 12:21


















draft saved

draft discarded




















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.





Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


Please pay close attention to the following guidance:


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53392304%2fwriting-an-array-of-integers-into-a-file-using-c%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Tonle Sap (See)

I get strange results when I access the Sqlitedatabase with Unity C# via XAMPP

Guatemaltekische Davis-Cup-Mannschaft