Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write an int using fwrite()

Tags:

c

file-io

Let's say I have a int largeInt = 9999999 and char buffer[100], how can I convert largeInt into a string (I tried buffer = largeInt, doesn't work) and then fwrite() to a file stream myFile?

Now what if I want to write "The large number is (value of largeInt)." to myFile?

like image 803
Dylan Czenski Avatar asked May 12 '26 11:05

Dylan Czenski


2 Answers

An example :

int largeInt = 9999999;
FILE* f = fopen("wy.txt", "w");
fprintf(f, "%d", largeInt);

Please refer this link:http://www.cplusplus.com/reference/cstdio/fprintf/

If you want use fwrite,

char str[100];
memset(str, '\0', 100);
int largeInt = 9999999;
sprintf(str,"%d",largeInt);

FILE* f = fopen("wy.txt", "wb");
fwrite(str, sizeof(char), strlen(str), f);
like image 178
BlackMamba Avatar answered May 14 '26 01:05

BlackMamba


You may use the non-standard itoa() function as described here and convert the number to string and then format your sentence using sscanf to format it.

itoa() : Converts an integer value to a null-terminated string using the specified base and stores the result in the array given by str parameter.

Then write the sentence to your file using fwrite.