Attempted to switch from using syscalls(program1) to the stdio library(program2)
But while I get bytes/sec and everything else in first program, second program only prints "write: Success". How can I get the same output as program1?
#include "iobench.h"
int main() {
// opens a file called `data` with the O_SYNC
int fd = open("data", O_WRONLY | O_CREAT | O_TRUNC, 0666);
if (fd < 0) {
perror("open");
exit(1);
}
// writes the characer '6' to the file
size_t size = 5120000;
constchar* buf = "6";
double start = tstamp();
size_t n = 0;
while (n < size) {
ssize_t r = write(fd, buf, 1);
if (r != 1) {
perror("write");
exit(1);
}
// with some frequency (defined in iobench.h), prints out
// how long it takes to complete the write.
n += r;
if (n % PRINT_FREQUENCY == 0) {
report(n, tstamp() - start);
}
}
close(fd);
report(n, tstamp() - start);
fprintf(stderr, "\n");
}
I'd rather suggest: size_t r = fwrite(buf, sizeof(char), strlen(buf), fp);
size
Size in bytes of each element to be written. count
Number of elements, each one with a size of size bytes.
Here strlen() gives you the number of characters (excluding the terminating NULL char) in the C string to be written. And the size of each character is sizeof(char), which is 1 on almost all platforms.
sizeof(buf) would give you the size of a charpointer, and sizeof(*buf) would give you the size of a singlechar. The latter "works" as long as the C string contains exactly one character, but fails otherwise!
BTW: Return value of fwrite() is size_t, not ssize_t.
_______________
Another option, which is usually preferred when writing out strings: