1

I need to call a function from main. The side effect of the function is to print a new line char. Is there any way to remove that char?

The program looks like:

#include "header_file.h"
#include <stdio.h>

int main() {
  for (int i=0; i<1e5; i++) {
    int A = HEADER_SPACE::func_linebreak();
    printf("\b");
  }
  printf("1234");
  return 0;
}

I don't know if it is cout << endl; or printf("\n"); in the func_linebreak() function. I don't know if there is fflush(stdout); inside it.

One thing for sure is that I always run the binary/exe file with output redirect: ./my_main.out >> outFile.txt in Linux system.

This post does not work here.


It turns out that the most convenient way to remove the newline sign is to disable the printing from beginning. In my current application, fortunately, I'm able to do that.

My problem has been solved, but I won't delete this post since there might be cases when the source code is unavailable, and some one may still wants to achieve the same goal.

user3813057
  • 891
  • 3
  • 13
  • 31
  • Heh. you could replace `stdout` with a pipe for the duration of the call, then read the pipe and strip the newline. (probably not practical). – lockcmpxchg8b Mar 09 '18 at 03:24
  • 1
    Can you modify the function to not print the character in the first place? That's usually a lot easier and more portable. – user4581301 Mar 09 '18 at 03:30
  • I'm just going to leave it here: this is going to be very painful. – Lightness Races in Orbit Mar 09 '18 at 03:38
  • If the output of the program is being redirected to a file, why does the newline need to be removed at all? If you have another program which is reading that output file, modify that program to cope properly with the potential presence of extraneous newlines. – Peter Mar 09 '18 at 04:54

1 Answers1

0

On Linux, you can use the dup2() system call to change stdout and stderr (i.e. the file descriptors 1 and 2). To discard output you can just open /dev/null and duplicate to that.

TypeIA
  • 16,916
  • 1
  • 38
  • 52