Thread: Please Help with C code regarding time.h functions and FILE readings

  1. #1
    Registered User
    Join Date
    Sep 2012
    Posts
    4

    Please Help with C code regarding time.h functions and FILE readings

    Hi everyone,

    What I am trying to do is to read in a file, line by line, and write to a new file until the EOF. I also want to find out the time it takes for the program to run, one for CPU and one for real world time. My code is kind of a mess right now so I can use some help. Much appreciated.

    Code:
    #include <stdio.h>
    #include <time.h>
    #include <string.h>
    
    
    
    
    int main(void)
    {
        clock_t begin, finish;
        double time_spent;
        
        
        
        time_t start, end;
        double duration = 0;
        
        begin = clock();
        
        time(&start);
        
        FILE *fpr, *fpw;
        
        char file_name_r[]="";
        char file_name_w[]="";
        char string[BUFSIZ];
     
        
        printf( "\nEnter the name of the file to write to: " );
        scanf("%s", &file_name_w);
        
        printf( "Enter the name of the file to open: " );
        scanf("%s", &file_name_r);
        
        
        fpr = fopen(file_name_r, "r");
        
        if(fpr == NULL)
        {
            printf( "\n%s\ File NOT FOUND!",file_name_r);
        }
        
        while (fgets(string, sizeof string, fpr) != NULL){
            
            fpw = fopen(file_name_w, "w");
            fprintf(fpw, "%s", string);
            
        }
        
            
        fclose(fpr);
        fclose(fpw);
        
        return 0;
        
        end = clock();
        
        time_spent = (double)(finish - begin) / CLOCKS_PER_SEC;
        printf("Time elapsed in CPU milli-seconds : %f milli-seconds/n", time_spent);
        
        
        
        time(&end);
        
        duration = difftime(end, start);
        duration = duration/1000;
        printf("Time elapsed in Wall-clock : %f milli-seconds\n", duration);
        
        
    }
    Last edited by hankremix; 09-23-2012 at 02:42 PM.

  2. #2
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,612
    When I compiled your code I got:

    Code:
    C:\Users\Josh2\Documents\foo\main.c||In function 'main':|
    C:\Users\Josh2\Documents\foo\main.c|22|warning: ISO C90 forbids mixed declarations and code|
    C:\Users\Josh2\Documents\foo\main.c|30|warning: format '%s' expects type 'char *', but argument 2 has type 'char (*)[1]'|
    C:\Users\Josh2\Documents\foo\main.c|33|warning: format '%s' expects type 'char *', but argument 2 has type 'char (*)[1]'|
    C:\Users\Josh2\Documents\foo\main.c|40|warning: unknown escape sequence: '\040'|
    C:\Users\Josh2\Documents\foo\main.c|56|warning: will never be executed|
    ||=== Build finished: 0 errors, 5 warnings ===|
    I think most of these are easy to understand.

    Remember that strings do not need & if you are going to pass them into scanf(). The string in line 40 appears to have a stray \, and you will want to give file_name_r and file_name_w a length.

    Code:
        while (fgets(string, sizeof string, fpr) != NULL){
            
            fpw = fopen(file_name_w, "w");
            fprintf(fpw, "%s", string);
            
        }
    Weird. You only need to open a file once and after you are finished you only need to close it once.

  3. #3
    Registered User
    Join Date
    Sep 2012
    Posts
    4
    Thanks for the reply whiteflags,

    I updated my code based on your comments.

    My concerns would be:

    Is my file reading code correct and does what I intended?

    Is the placement of the start time and end time functions in the right place. One to calculate the time the program uses the CPU and one from the start of program to the end of program.

    Also, I am not sure where to put the txt files, or should I include the path to the file somewhere in the code?

    Thanks a whole bunch guys!

    Code:
    #include <stdio.h>
    #include <time.h>
    #include <string.h>
    
    
    
    
    int main(void)
    {
        clock_t begin, finish;
        double time_spent;
        
        
        
        time_t start, end;
        double duration = 0;
        
        begin = clock();
        
        time(&start);
        
        FILE *fpr, *fpw;
        
        char file_name_r[100]="";
        char file_name_w[100]="";
        char string[BUFSIZ];
     
        
        printf( "\nEnter the name of the file to write to: " );
        scanf("%s", file_name_w);
        
        printf( "Enter the name of the file to open: " );
        scanf("%s", file_name_r);
        
        
        fpr = fopen(file_name_r, "r");
        
        if(fpr == NULL)
        {
            printf( "\n%s File NOT FOUND!",file_name_r);
        }
        
        fpw = fopen(file_name_w, "w");
    
        while (fgets(string, sizeof string, fpr) != NULL){
            
            fprintf(fpw, "%s", string);
            
        }
        
            
        fclose(fpr);
        fclose(fpw);
        
        return 0;
        
        end = clock();
        
        time_spent = (double)(finish - begin) / CLOCKS_PER_SEC;
        printf("Time elapsed in CPU milli-seconds : %f milli-seconds/n", time_spent);
        
        
        
        time(&end);
        
        duration = difftime(end, start);
        duration = duration/1000;
        printf("Time elapsed in Wall-clock : %f milli-seconds\n", duration);
        
        
    }
    Last edited by hankremix; 09-23-2012 at 03:26 PM.

  4. #4
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,612
    Also, I am not sure where to put the txt files, or should I include the path to the file somewhere in the code?
    I think the best solution right now would be to ask the user to provide the complete path to the file if that is really a concern.

    Is the placement of the start time and end time functions in the right place. One to calculate the time the program uses the CPU and one from the start of program to the end of program.
    No. I thought the warning my compiler gave was clear on this. Line 57 and everything after it will not be executed. Once the main function returns, you are done.

    Is my file reading code correct and does what I intended?
    You should test and see for yourself. You're not too far away from the time when you should be debugging.

  5. #5
    Registered User
    Join Date
    Sep 2012
    Posts
    4
    I understand that I should be debugging. However, because I am not sure where to put the files, I couldn't test this yet. I am coding in Xcode btw. Sorry if I didnt understand the warnings, since im relatively inexperienced in coding. Can you please elaborate on my second question, and maybe suggest ways for me to fix this. Thanks again

  6. #6
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    I like to leave the paths out, and just use the filenames. Then I know the files will always be in the same directory as the program - input, output, temp files used, etc. All right there.

    Your start and begin variables should be set at line 34, not before the user types in stuff. Otherwise it's just timing the user's typing, also. Time end should be line 58, otherwise you're timing the printing of some info, and a calculation.

    Think of a race, when does the stopwatch stop? Exactly when the runner crosses the line, not a bit later.

  7. #7
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,612
    Can you please elaborate on my second question, and maybe suggest ways for me to fix this. Thanks again
    As far as I can tell the only problem is that the return statement is out of place. return 0; must be the last statement in main(), because the program will end. That is why the compiler gave the warning about code that will not be executed.

    In truth, I spotted that right away. I had to flip a compiler switch to get the output I wanted though. It would still be important in any case. Functions can only end once, and when they do, control of the flow of the program will be with the code that called the function. So if you called a function named hello(); in main(), when hello() ended, control would be back in main().

    However, because I am not sure where to put the files
    I see what you are really asking now. Unfortunately I am not really sure either. X-Code should have a project directory, which is where the IDE looks for stuff like extraneous files. A reasonable guess for where is the same place the executable is kept after you build. I still think my original suggestion is the best, so that the files can be kept anywhere. Asking the user where the file is removes guess work, and it is secure.

  8. #8
    Registered User
    Join Date
    Sep 2012
    Posts
    4
    I appreciate all the help on this. I updated the start time to right before the read file opened and the end right after both files closed. Also placed return 0; as the last line in the code.

    I will try to test this with the files in place.

    Thanks a lot guys
    Last edited by hankremix; 09-23-2012 at 04:16 PM.

  9. #9
    Registered User ledow's Avatar
    Join Date
    Dec 2011
    Posts
    435
    I'm not sure that what you test will actually give you two different times at all, either (or, at least, they will always return two times which - to within their accuracy - always differ by exactly the same amount, irrespective of the time taken or the size of the files copied).

    What makes you think that you're measuring "CPU time" versus "real-world time"? clock() returns the number of clock ticks elapsed, and time() the number of seconds elapsed and as you can see they will be very closely correlated by the CLOCK_PER_SEC fixed ratio anyway. I don't think you're measuring what you think you are, and if you're after total CPU time used rather than clock time (i.e. trying to get an impression of I/O time, etc.) then you're really out of luck with standard C unless you use a machine-specific library or function to do that job for you. "clock" is representative of little in modern machines because they don't run at constant ticks per seconds, and even when they used to, that number was never representative anyway (i.e. some things take more ticks to execute than others anyway).

    All you've done is made two time measurements of different accuracy of slightly different portions of your program whose answers will hardly, if ever, vary from each other.

    - Compiler warnings are like "Bridge Out Ahead" warnings. DON'T just ignore them.
    - A compiler error is something SO stupid that the compiler genuinely can't carry on with its job. A compiler warning is the compiler saying "Well, that's bloody stupid but if you WANT to ignore me..." and carrying on.
    - The best debugging tool in the world is a bunch of printf()'s for everything important around the bits you think might be wrong.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. [HELP] Code to Convert Army Time to Normal Time?
    By Kipper DeVera in forum C++ Programming
    Replies: 9
    Last Post: 08-21-2011, 11:50 PM
  2. Replies: 10
    Last Post: 08-29-2007, 05:59 AM
  3. delay between two readings from a buffer?
    By Hunsson in forum C Programming
    Replies: 2
    Last Post: 03-30-2004, 05:28 PM
  4. time functions
    By sw9830 in forum C Programming
    Replies: 1
    Last Post: 02-28-2003, 02:55 PM
  5. Where to find the code for Header File FUnctions
    By vsriharsha in forum C Programming
    Replies: 1
    Last Post: 04-02-2002, 12:37 PM