3

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?

Dylan Czenski
  • 1,305
  • 4
  • 29
  • 49
  • 3
    Do you want `largeInt` to be written to the file in binary or as text? – fuz Nov 06 '15 at 07:36
  • 3
    You *do* know about [`fprintf`](http://en.cppreference.com/w/c/io/fprintf)? – Some programmer dude Nov 06 '15 at 07:37
  • Why do you want to use `fwrite`? Or does the function used not matter, you just want it as a string on the file? (`fwrite` is usually the wrong choice if you want to write text to a file.) – Thomas Padron-McCarthy Nov 06 '15 at 07:37
  • @Joachim Pileborg fprintf() decreases speed as it should format the text –  Nov 06 '15 at 07:39
  • 3
    @Ehsan: Don't worry about small performance differences until you know that you really need the speed, and that you have profiled your program to find where the bottlenecks are. – Thomas Padron-McCarthy Nov 06 '15 at 07:40
  • 2
    @Ehsan Which still needs to be done to "convert" the number to a string. – Some programmer dude Nov 06 '15 at 07:40
  • @FUZxxl I want to write it as text. @JoachimPileborg I do know about `fprintf()` I think it would be better in this scenario. but I want to see how `fwrite()` works just in case I need to use it. Also I wonder how to convert a `int` that's more than 1 digit to a string in C? – Dylan Czenski Nov 06 '15 at 07:44
  • 1
    Have you looked at [`sprintf`](http://en.cppreference.com/w/c/io/fprintf)? – R Sahu Nov 06 '15 at 07:44

2 Answers2

3

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);
BlackMamba
  • 10,054
  • 7
  • 44
  • 67
2

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.

  • Thank you so much. And from the documentation I noticed that `itoa()` has a return value, which is a pointer to the resulting null-terminated string, same as parameter string... I wonder why it is designed this way. I thought strings are arrays in C, and arrays don't need to be returned. – Dylan Czenski Nov 06 '15 at 08:01
  • `itoa()` is definitely non-standard. See http://stackoverflow.com/questions/190229/where-is-the-itoa-function-in-linux – Andrew Henle Nov 06 '15 at 11:35