Thread: Newbie help writing time to a text file

  1. #1
    Registered User
    Join Date
    Apr 2007
    Posts
    6

    Newbie help writing time to a text file

    Hi, I'm pretty new to this. I have the following code in a script that prints out the time (including milliseconds), I really need this data to be written to a .txt file rather than just being printed out to the console. Can someone please explain how I do this? :

    Code:
    gettimeofday(&tv, &tz);
    tm=localtime(&tv.tv_sec);
    printf(" %d:%02d:%02d %d \n", tm->tm_hour, tm->tm_min, tm->tm_sec, tv.tv_usec/1000);


    Thanks, Geester

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    asctime()
    strftime()
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Registered User
    Join Date
    Oct 2001
    Posts
    2,934
    > really need this data to be written to a .txt file rather than just being printed out to the console.
    Code:
    const char filename[] = "file.txt";
    FILE *fp;
    .
    .
    if (fopen(filename, "w") == NULL)
    {
        printf("Unable to open file: %s\n", filename);
        return EXIT_FAILURE;
    }
    fprintf(fp, " %d:%02d:%02d %d \n", tm->tm_hour, tm->tm_min, tm->tm_sec, tv.tv_usec/1000);
    
    fclose(fp);

  4. #4
    Registered User
    Join Date
    Apr 2007
    Posts
    6
    Thanks for the speedy replies

    geester

  5. #5
    Registered User
    Join Date
    Oct 2006
    Posts
    250
    Alternatively you can just reroute the output from your program to a text file from the console:

    program.exe > textfile

  6. #6
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Kinda makes it hard to see what it expects of you that way, doesn't it?


    Quzah.
    Hope is the first step on the road to disappointment.

  7. #7
    Registered User
    Join Date
    Oct 2001
    Posts
    2,934
    And in addition to the user input anomaly, maybe only the time goes to that file, and other output goes to other places.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Problem Writing to Text File
    By slowcoder in forum C Programming
    Replies: 2
    Last Post: 08-22-2007, 12:19 PM
  2. Reading Character at a time from a text file
    By Giania in forum C Programming
    Replies: 8
    Last Post: 02-25-2006, 03:17 PM
  3. writing a number to a text file
    By Erkan in forum C Programming
    Replies: 2
    Last Post: 10-31-2005, 09:18 AM
  4. Batch file programming
    By year2038bug in forum Tech Board
    Replies: 10
    Last Post: 09-05-2005, 03:30 PM
  5. Function is called and I am trying to open a file
    By tommy69 in forum C Programming
    Replies: 88
    Last Post: 05-06-2004, 08:33 AM