Thread: output to file

  1. #1
    Registered User
    Join Date
    Oct 2001

    output to file


    I've written a program and want the output to go to file. My data is stored in a linked-list and a function is called to loop through the list and print it, using something like

    printf("%s\n", mylist->item1);

    However, I now want the user to be able to print the results to file, specifiying the filename. So the user is prompted to input a filename, that file is created and the results are stored in that file.

    Do I now have to use puts(), or is there a way that I can just open a new file and specify that all printf's are printed there?

    NB:- I have tried using the redirection (>) operator but because my program is reading from one file and writing to another, this redirects the prompt for the input file to the output file, so the user is not asked for input.

    Appreciating any help...


  2. #2
    Hi Bill,

    you could replace the printf's with fprintf's

    fprintf('filename',string,other arguments);

    then if you want to print to the screen just have a string in place of filename and make that string stdout.

    If you want to print to the file make the string the filename

    dont know if this solves the problem though as it dosent involve redirection (was a passing thought!)

  3. #3
    Registered User
    Join Date
    Jan 2002

    another option

    the fprintf is a good option. If you prefer to work with file handles instead of file streams ( pipe info, write to sockets, or serial ports ) though, you can write an fdprintf function like this.

    int fdprintf(int fd, const char *fmt, ...)
    char buf[512];
    int len;
    va_list args;

    va_start(args, fmt);
    vsprintf(buf, fmt, args);

    return ( write(fd, buf, strlen(buf)) );

    then just do...

    file = open( "filename.txt", O_RDWR | O_TRUNC | O_CREAT );

    fdprintf(file, "some text for the file\n");

    close( file );
    ~good monkeys, Excelent typewritters!...

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 3
    Last Post: 03-04-2005, 02:46 PM
  2. Unknown Memory Leak in Init() Function
    By CodeHacker in forum Windows Programming
    Replies: 3
    Last Post: 07-09-2004, 09:54 AM
  3. archive format
    By Nor in forum A Brief History of
    Replies: 0
    Last Post: 08-05-2003, 07:01 PM
  4. System
    By drdroid in forum C++ Programming
    Replies: 3
    Last Post: 06-28-2002, 10:12 PM
  5. Simple File Creation Algorithm
    By muffin in forum C Programming
    Replies: 13
    Last Post: 08-24-2001, 03:28 PM