2

I am trying to write to stdout using only Linux system calls described in section 2 of the manual (http://man7.org/linux/man-pages/dir_section_2.html).

ssize_t write(int fd, const void *buf, size_t count);

is the function I am trying to use, however the I am trying to incorporate format specifiers into the buffer. Ideally it would work like so:

char *adjective = argv[1];
write(1, "This is a %s example\n", adjective, 19 + strlen(adjective));

But I obviously cannot do this. How would I go about getting something similar done?

Also, I know strlen() isn't a part of section 2 of the Linux system calls. I'm including it for simplicity since counting the length of the buffer isn't part of my question.

adhdj
  • 352
  • 4
  • 17

1 Answers1

1

Use sprintf() to format into a buffer, which you then write:

char buffer[BUFSIZE];
int size = snprintf(buffer, BUFSIZE, "This is a %s example\n", adjective);
write(STDOUT_FILENO, buffer, strlen(buffer));

If you can't use sprintf(), just write each string separately.

write(STDOUT_FILENO, "This is a ", sizeof "This is a ");
write(STDOUT_FILENO, adjective, strlen(adjective));
write(STDOUT_FILENO, " example", sizeof " example");
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • Unfortunately for this assignment, I cannot use snprintf() as it is not in section 2 of the Linux manual. – adhdj Oct 11 '17 at 21:03
  • Then you can't use format specifiers, they're part of the `printf()` family of functions. – Barmar Oct 11 '17 at 21:05
  • Gotcha! I was starting to suspect I couldn't do it. Thank you! – adhdj Oct 11 '17 at 21:05
  • Are you sure you have to use format specifiers? If you do, it sounds like you're supposed to implement your own version of `printf()`. – Barmar Oct 11 '17 at 21:06
  • An example string includes use of format specifiers, (""The elapsed time to execute %d copies of \"%s\" on %d processors is %7.3fsec\n") and the non-function requirements state that I can only use Linux system calls from section 2 of the manual. – adhdj Oct 11 '17 at 22:00
  • Then I guess you're supposed to write your own implementation of `printf()`. And if you can only use section 2 functions, that also means you will have to write your own code that converts integers and floating points to text. In other words, you've been tasked to reimplement a huge amount of the standard C library. – Barmar Oct 11 '17 at 23:46
  • I hope you don't have a short deadline, you're talking about weeks of work for an experienced programmer. – Barmar Oct 11 '17 at 23:49
  • Thanks @Barmar. I just finished. Unfortunately, I missed the deadline by about 11 months but it was worth the journey! – adhdj Oct 04 '18 at 01:12