Problem scenario: Using the C programming language, you want to write a program that produces a file (we'll call it contint.txt) that has the following content:
1
2
3
4
5
6
7
8
9
a
b
c
d
e
f
Solution
Overview of the approach: Hexadecimal numbers use base 16. So "a" is the equivalent of 10, and "f" is the equivalent of 15. You want to use "%x" parameter associated with the fprintf function to convert regular (base 10) integers into their hexadecimal equivalents.
1. Create this file (we'll call it contint.c):
#include<stdio.h>
int main()
{
FILE *contintptr;
int x;
contintptr=fopen("contint.txt", "w");
if (!contintptr)
return 1;
for (x=1; x<=15; x++)
fprintf(contintptr,"%x\n", x); //the "%x" translates the variable into a hexadecimal.
fclose(contintptr);
return 0;
}
//end of file
2. Compile it with this command:
gcc contint.c
3. Run the compiled binary: ./a.out
4. You are done. View contint.txt for your output.