I have a structure, that i want to write to a regular file as one record, with comma delimited fields. For example
struct A {
int a;
int b;
} test;
Given test.a=1 and test.b = 2, the regular file will have a corresponding 1,2 as one line record. Another requirement, is that i want to write the entire structure with one system call. So, i created a char buffer[10], stored the value of int a,b into buffer, with comma delimited and a new line character and used Linux system write() call to write the buffer.
The problem is that the record ends up as binary in the file. Which is intuitive as i took away the “typeness” from the variables, the momment i stored them in a char array. I can use standard io, but i would like to learn, how i can achieve the desired results with standard linux system calls with the outlined constraints. How can i preserve the “typness” of a variable. By typeness i mean that if the variable is of type int, the regular file should have human readable digits.
What you are looking to do is something like
fprintf(fh, "%d,%d\n", test.a, test.b);, if you open the output file withfopen. If you really must usewrite()for some reason, you cansprintf(buffer, "%d,%d\n", test.a, test.b); write(fd, buffer, strlen(buffer));.