P basak
P basak

Reputation: 5004

saving different type variables in a formated string to a text file in C

I want to save the value of different types of variable in a comma separated csv file. right now I have something like

printf("[%-2d]|%08x%s[%s][%s][%08x][%08x]", a,b,c,d,e,f,g);

what I want is to write in a text file the values like:

a,b,c,d,e,f,g

Here are the constraints. a is an unsigned integer and must be saved just like the printf formatted string %-2d,

b,f, and, g are integers but i need to save the hexadecimal value of those variables with the same format used in printf, i.e. %08x.

I am writing a C program.

Upvotes: 0

Views: 109

Answers (2)

Floris
Floris

Reputation: 46415

Does the following work:

FILE* filePointer
filePointer = fopen("myFileName.csv", "w");
fprintf(filePointer, "%-2d, %08x, %s, %s, %s, %08x, %08x\n", a,b,c,d,e,f,g);
fclose(filePointer);

Upvotes: 3

ArtemB
ArtemB

Reputation: 3632

printf has its cousin fprintf which will happily print whatever you want into a file you've opened/created with fopen

fprintf(stream, "%-2d, %08x, %s, %s, %s, %08x, %08x\n", a,b,c,d,e,f,g);

Upvotes: 4

Related Questions