fork download
  1. #include <unistd.h>
  2. #include <string.h>
  3. #include <string>
  4.  
  5. using namespace std;
  6.  
  7. int main(int argc, char ** argv)
  8. {
  9. (void)argc, (void)argv;
  10.  
  11. const unsigned int bufsize = 16384;
  12. char input_buffer[bufsize];
  13. string output_buffer;
  14. string what_to_append = "\t2\n";
  15.  
  16. auto flush_output = [&](bool force) {
  17. if (force || output_buffer.size() > bufsize)
  18. {
  19. write(1, output_buffer.data(), output_buffer.size());
  20. output_buffer.resize(0);
  21. }
  22. };
  23.  
  24. for (;;)
  25. {
  26. ssize_t bytes_read = read(0, input_buffer, sizeof(input_buffer));
  27. if (bytes_read < 0)
  28. {
  29. perror("read failed");
  30. return 1;
  31. }
  32. else if (bytes_read == 0)
  33. {
  34. break;
  35. }
  36.  
  37. for (char * in_ptr = input_buffer;;)
  38. {
  39. ssize_t remaining = input_buffer + bytes_read - in_ptr;
  40. if (remaining <= 0) break;
  41.  
  42. char * eol = (char*)memchr(in_ptr, '\n', remaining);
  43. if (!eol)
  44. {
  45. output_buffer.append(in_ptr, remaining);
  46. flush_output(false);
  47. break;
  48. }
  49. output_buffer.append(in_ptr, eol - in_ptr);
  50. output_buffer.append(what_to_append);
  51. flush_output(false);
  52. in_ptr = eol + 1;
  53. }
  54. }
  55. flush_output(true);
  56. }
  57.  
Success #stdin #stdout 0s 3268KB
stdin
abc
def
stdout
abc	2
def	2