1. Welcome to the new MacRumors forums. See our announcement and read our FAQ

Mac terminal

Discussion in 'Mac Programming' started by phil05, Feb 4, 2009.

  1. macrumors newbie

    I have compiled a C++ program in the terminal and i want to output the results to a text file (results.txt) instead of the terminal.
    What command do i use to do this?

  2. macrumors 6502a

    Run your program and redirect it's output to a file. If you program is "hello", type
    ./hello > results.txt
  3. macrumors member

    ./your_program_name > file.txt
    or >> if you want to append to the file.
  4. macrumors newbie

    Thanks for the help guys.
  5. macrumors 6502a

    You can also pipe it to tee if you want to see the results on screen and store it in a file:

    ./your_program | tee output_file_name.txt
  6. macrumors 6502a

    Cool - I wasn't aware of tee.

    Too many goodies in unix to learn them in one sitting.
  7. macrumors newbie


    Doing it in code

    Why don't you do it in the code of your program?

    #include <stdio.h>
    #include <stdlib.h>

    // create a file pointer and the string to print to the file
    FILE *fp;
    char buffer[] = "This is my result string";

    // open the file and exit() from stdlib.h if it does not exist
    fp = fopen("results.txt","w");
    if (fp == NULL) exit(1);

    // print the string to the file
    fprintf(fp,"result: %s", buffer);

    // close the file to save the changes

    return 0;

Share This Page