Advertisement
Help Keep Boards Alive. Support us by going ad free today. See here: https://subscriptions.boards.ie/.
If we do not hit our goal we will be forced to close the site.

Current status: https://keepboardsalive.com/

Annual subs are best for most impact. If you are still undecided on going Ad Free - you can also donate using the Paypal Donate option. All contribution helps. Thank you.
https://www.boards.ie/group/1878-subscribers-forum

Private Group for paid up members of Boards.ie. Join the club.

File input/output query

  • 06-05-2006 08:10PM
    #1
    Closed Accounts Posts: 113 ✭✭


    I am having a bit of difficulty with this question.Any help would be great thanks

    #include <stdio.h>
    void main(void)
    {
    FILE *fptr1, *fptr2;
    int inp;
    fptr1 = fopen(“input.dat”, “r”);
    fptr2 = fopen(“output.dat”, “w”);
    while (fscanf(fptr1, “%d”, &inp)==1){
    if (inp >= 1 && inp <= 5){
    fprintf(fptr2, “%d,”, inp);
    }
    }
    fclose(fptr1);
    fclose(fptr2);
    }
    (i) Suppose the file input.dat contains the following data:
    0
    2
    -4
    6
    -1
    5
    Complete this sentence:
    After executing this program, the file output.dat contains ______________ .
    (ii) Re-write the above program so that it writes all the even values in a file called
    input2.dat to a file called output2.dat


    in reference to part(ii) could someone tell me how I'd go about rewriting the program so it would take in odd values.Is this the correct procedure

    #include <stdio.h>
    void main(void)
    {
    FILE *fptr1, *fptr2;
    int inp;
    fptr1 = fopen("input2.dat", "r");
    fptr2 = fopen("output2.dat", "w");
    while (fscanf(fptr1, "%d", &inp)==1){
    if ((inp%2)!=0){
    fprintf(fptr2, "%d,", inp);
    }
    }
    fclose(fptr1);
    fclose(fptr2);
    }
    I'm unsure whether this right or not and I can't seem to install a c compiler on my PC for some reason it would let me.


Comments

  • Closed Accounts Posts: 4,943 ✭✭✭Mutant_Fruit


    The modulus operator returns the remainder when you divide the number 'a' by 'b'. So you're perfectly right with your usage of it. Another way of writing it would be:

    if(inp%2 == 1) //i.e. remainder IS 1.

    EDIT: Whoops, misinterpreted the problem... First put [ CODE ] tags around your code, it makes it more readable. Then, write a comment beside each line of code telling us what you think it's doing. It should be obvious enough what is happening once you do that.


  • Registered Users, Registered Users 2 Posts: 5,333 ✭✭✭Cake Fiend


    Looks good, you could even shorten it by just using:

    if (inp%2)

    Remember kids, if it's easy to read, it's not real C code!
    if(inp%2 == 1) //i.e. remainder IS 1

    Only problem with that is that it won't pick up negative numbers.


Advertisement