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?

8
  • 3
    Do you want largeInt to be written to the file in binary or as text? Commented Nov 6, 2015 at 7:36
  • 3
    You do know about fprintf? Commented Nov 6, 2015 at 7:37
  • 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. Commented Nov 6, 2015 at 7:40
  • 2
    @Ehsan Which still needs to be done to "convert" the number to a string. Commented Nov 6, 2015 at 7:40
  • 1
    Have you looked at sprintf? Commented Nov 6, 2015 at 7:44

2 Answers 2

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);
Sign up to request clarification or add additional context in comments.

Comments

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.

2 Comments

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.
itoa() is definitely non-standard. See stackoverflow.com/questions/190229/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.