Reputation: 4149
I am having trouble getting write() system call to write in a file. So far, I manage to only print gibberish into a file that is said to be a binary file. I know that we must somehow preformat write().
How do I actually get write() to create/write in a text file?
void writeNumbers(int array[], int size, char* fname, int hexFlag) {
int fp;
int i;
char buf[512];
fp = open(fname, O_WRONLY | O_CREAT | O_APPEND);
if (fp < 0) {
close(fp);
char msg[] = "Cannot write";
write(STDOUT_FILENO, msg, sizeof(msg) - 1);
exit(1);
}
if (hexFlag == 0) {
for (i = 0; i < size; i++) {
snprintf(buf, sizeof(int), "%d ", array[i]);
write(fp, buf, sizeof(buf));
}
} else {
for (i = 0; i < size; i++) {
snprintf(buf, sizeof(int), "%x ", array[i]);
write(fp, buf, sizeof(int));
}
}
write(fp, "message", sizeof(buf));
close(fp);
}
Here I am trying to print an array of ints either in hexadecimal or decimal formats.
Upvotes: 0
Views: 1165
Reputation: 70981
snprintf()
returns the number of characters printed into the buffer passed. Also it takes the maximum number of characters to print to the buffer as second argument, that typically is the size of the buffer, but also could be few.
You want to write out exactly the number of characters, as returned by snprintf()
.
if (hexFlag == 0) {
for (i = 0; i < size; i++) {
int result = snprintf(buf, sizeof(buf), "%d ", array[i]);
if (0 > result)
{
write(STDERR_FILENO, "snprintf() failed.\n", strlen("snprintf() failed.\n"));
}
else
{
write(fp, buf, result);
}
}
}
else
...
As general advise: Carefully read a function's documentation.
Upvotes: 2
Reputation: 4767
Each call to snprintf
should take sizeof(buffer)
instead of sizeof(int)
. Each call to write
should take strlen(buf)
as its 3rd argument.
Upvotes: 2