2 Replies - 465 Views - Last Post: 17 November 2012 - 04:38 AM Rate Topic: -----

#1 erkant  Icon User is offline

  • D.I.C Head

Reputation: 2
  • View blog
  • Posts: 108
  • Joined: 26-October 10

Writing the console output to a file?

Posted 17 November 2012 - 04:10 AM

I'm creating a console application in C, which will do quite a lot of computation and mathematics, and will print a lot of results on the console. The point is that I want to write those outputs directly to a file. Is there any method, or piece of code that can help me to write the console output to a .txt file?
Is This A Good Question/Topic? 0
  • +

Replies To: Writing the console output to a file?

#2 Xupicor  Icon User is offline

  • Nasal Demon
  • member icon

Reputation: 249
  • View blog
  • Posts: 582
  • Joined: 31-May 11

Re: Writing the console output to a file?

Posted 17 November 2012 - 04:25 AM

First, there are different approaches to this problem. You can use <stdio.h> and functions there, like fopen(), fclose(), fwrite(), fput/s(), fprintf(), etc, to open, write, close files. But if your output could also be handy in form of standard output display, then maybe you should just output it like that (using printf(), etc).
You can always run your program like this then:
$ ./myapp
THIS IS THE DISPLAY
$ ./myapp > file.txt
$ cat file.txt
THIS IS THE DISPLAY
$ ./myapp >> file.txt
$ cat file.txt
THIS IS THE DISPLAY
THIS IS THE DISPLAY
$

If you're not familiar with terminal, then this: ./myapp just runs your program, this: ./myapp > file.txt redirects standard output of that program to a file, so everything you output using "normal" io functions like printf(), fputs(), etc - gets saved to a file. cat is not an animal, it's a utility app that here just reads a given file and outputs it on standard output. ;) ./myapp >> file.txt is basically the same as above, but it appends to file - whereas > will erase previous file contents.

You can do this all in windows too, you just don't need ./ to run the application in command prompt. Oh, and you'd need to use type instead of cat, I don't quite remember I last time used Windows console without *nix toolset installed, so... ;)
Was This Post Helpful? 1
  • +
  • -

#3 erkant  Icon User is offline

  • D.I.C Head

Reputation: 2
  • View blog
  • Posts: 108
  • Joined: 26-October 10

Re: Writing the console output to a file?

Posted 17 November 2012 - 04:38 AM

Thank you very much Xupicor.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1