2

I know the general usage of the perror().

But right now, I want to export its result into a file, not the console. By the way, i run it in under the android emulator's adb shell.

Eitan T
  • 32,660
  • 14
  • 72
  • 109
kaiwii ho
  • 1,367
  • 7
  • 21
  • 40
  • 1
    Possible duplicate: see this [question](http://stackoverflow.com/questions/5483120/redirect-perror-output-to-fprintfstderr/5483164) – maverik May 30 '12 at 06:56
  • @maverik, but the "problem" is *this* question asks for a "a file", while the other question asks for output to stderr. So the answer happens to be quite similar, but the questions are quite a bit different. – Prof. Falken May 30 '12 at 07:02
  • `fprintf` is able to write to file just like `fputs` used in top-answer here. – maverik May 30 '12 at 07:05
  • @maverik, yes, I am not talking about the answers, but the wording of the questions, especially the titles. – Prof. Falken May 30 '12 at 07:14
  • @AmigableClarkKant, may be you're right. – maverik May 30 '12 at 07:25

3 Answers3

8

Use strerror() instead:

fprintf(logfile, "Something went wrong: %s\n", strerror(errno));

Or, you could redirect stderr to a file using dup2() and then carry on using perror().

EDIT: It was early when I answered this originally and my brain wasn't firing on all cylinders. There is no need to use sprintf() followed by fputs() as fprintf() can do it all (thanks to @maverik).

trojanfoe
  • 120,358
  • 21
  • 212
  • 242
2

You can redirect the whole stderr to that file. Here is a Unix way of doing this:

int fd = open("logfile", O_WRONLY); // 'fd' stands for 'file descriptor
close(2); // close stderr
dup(fd); // duplicate fd so that it's copy will be the lowest available value -- 2
tonytony
  • 1,994
  • 3
  • 20
  • 27
1

I believe you can direct the stderr to a file of your choosing, e.g $ ./program 2> errlog

HBY4PI
  • 89
  • 5