Thread: homework (reading and writing a file)

  1. #1
    Registered User
    Join Date
    Mar 2011
    Location
    Baltimore Md. USA
    Posts
    58
    I have a homework problem that I could really use some help on. Here are the directions: write a program to read a set of scores from a text file, count the scores over 90, copy the scores over 90 to a new file and print the number of scores over 90 to the monitor.
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    int newlist(int score);//function declaration
    
    FILE* spData;// file to read from
    FILE* spnewList;
    
    int score;//global variable dec.
    char name;
    
    int main()//main
    {
    
    int below = 0; //local declarations
    int count = 0;
    
    
     printf("This program will print scores over 90%\n");
    
    spData = fopen("TextFile1.txt", "r");
        if (!spData)
            {
            printf("Could not open file \a\n");
            exit (101);
            }//if open fails
            
    while (!EOF)
        fscanf(spData, " %d", &score);
    
            if (score > 90)
            {    count++;}
            else
                {below++;}
    
    printf("The number of scores above 90% are %d\n", count);
    printf("The number of scores below 90% are %d\n", below);
    
    newlist(score);
    
    
        return 0;
    }//main
    /*=================newlist==================*/
    int    newlist(int score)//writes info to new file
    {
    spnewList = fopen("Gradelist.txt", "w");//creates new file
    
        if (score > 90) 
            fprintf(spnewList, " %d", score);
        
        return 1;
    
    }//newlist
    I hope I did this correctly. I thought that this would be pretty easy but I can't see my problem. please help.

    I guess I should add that it does compile but doesn't open the file.
    Last edited by time4f5; 03-12-2011 at 07:15 PM.

  2. #2
    Registered User
    Join Date
    Dec 2007
    Posts
    2,675
    Is the file in the same location as the executable? If not, well then that's the problem.

    Code:
    while (!EOF)
        fscanf(spData, " %d", &score);
    
            if (score > 90)
            {    count++;}
            else
                {below++;}
    Using EOF is bad juju, and you're doing so incorrectly anyway. And the only thing in that while loop is the fscanf. If you want more than the line following a control statement like while to be executed, you need to use braces around that code ( {} ).
    Last edited by rags_to_riches; 03-12-2011 at 07:23 PM.

  3. #3
    Registered User
    Join Date
    Mar 2011
    Location
    Baltimore Md. USA
    Posts
    58
    Yeah, I attached it as existing and made sure it is in the project. I assume that is correct, we really didn't cover how to attach it in class, the book doesn't discuss it step by step. I just assumed you attached it the same way as the source code

  4. #4
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,909
    Global Variables Are Bad. Please move the definitions to main and pass them to any functions that need them.

    Code:
    while (!EOF)
        fscanf(spData, " %d", &score);
    That is not the loop you want. EOF is probably defined as -1 on your system, and thus !EOF is false, so the loop never executes. You shouldn't use the EOF marker for loop control anyway, even if you use the feof function: Cprogramming.com FAQ > Why it's bad to use feof() to control a loop.

    Read up on fscanf and control your loop using the return value of fscanf.

    Oh, and you have to use %% in a printf string to get an actual percent sign to show up, otherwise it thinks the following character is a format specifier (like %d, %c, etc).
    Last edited by anduril462; 03-12-2011 at 07:25 PM.

  5. #5
    Registered User
    Join Date
    Mar 2011
    Location
    Baltimore Md. USA
    Posts
    58
    anduril462 "Global variables are bad" - yeah, bad habit, I pass them in the functions anyway. I'll move them down. thanks.

    Ok. I have updated my code and read the link of feof. I have made all of the changes except the while loop. I get that fgets() is better to read whole lines of code, but I'm not grasping how to know when to stop. any help would be greatly appreciated.
    Last edited by time4f5; 03-12-2011 at 07:44 PM.

  6. #6
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,909
    I noticed a few more things:
    1. You need to check every score you read to see if it's over 90, so that belongs in your read loop along with incrementing your counts and writing it to file.
    2. Your newlist file opens Gradelist.txt every time but never closes it. You can open it once at the beginning of main and close it at the end. You can probably ditch the newlist function and move all your code into main.
    3. You also need to close TextFile1.txt when you're done.


    Posting your new code would be helpful. Also, you should read the docs on fscanf. You will find it easier than fgets, and you wont have to worry about possibly chopping a number in half with fgets if your buffer is too small for the line in your text file.

    Code:
    while (fscanf("%d", &score) != ?) {
    }
    Figure out what fscanf should return if it worked right and put it where the ? is.
    Last edited by anduril462; 03-12-2011 at 07:49 PM.

  7. #7
    Registered User
    Join Date
    Mar 2011
    Location
    Baltimore Md. USA
    Posts
    58
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    FILE* spData;// file to read from
    FILE* spGradelist;
    
    int main()//main
    {
    
    int below = 0; //local declarations
    int count = 0;
    int score;
    
     printf("This program will print scores over 90%\n");
    
    spGradelist = fopen("Gradelist.txt", "w");
    spData = fopen("TextFile1.txt", "r");
        if (!spData)
            {
            printf("Could not open file \a\n");
            exit (101);
            }//if open fails
            
    while ()
       { fscanf(spData, " %d", &score);
    
            if (score > 90)
            { fprintf(spGradelist, "%d", score);//creates new file
    			count++;}
            else
                {below++;}
    }
    printf("The number of scores above 90%% are %d\n", count);
    printf("The number of scores below 90%% are %d\n", below);
    
    
    
    fclose(spData);
    fclose(spGradelist);
    return 0;
    }//main
    here is the updated code, it my while loop is incomplete but everything else seems fine. I'm still looking into fscanf.

    ok, would it be stupid to put "1000" at the end of the list and when score is != 1000.

    here is my textfile1
    Billy 98
    Charlie 72
    Megan 89
    Mike 96
    Tim 91
    Adrian 79
    Rob 82
    Mark 91

    //it is just a generic list, it can be anything
    Last edited by time4f5; 03-12-2011 at 08:11 PM.

  8. #8
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,909
    Your loop isn't quite what I had in my previous post. You need to put fscanf in the loop condition.

    Using a value like 1000 to mark the end of list is not stupid, though it's arguably not the best solution here. What you suggested is called a sentinel value, and is common in things like linked lists, where one uses NULL to mark the end of the list. For integer data, like scores, a common value might be -1 since that's not a valid score under most circumstances. But keep after that fscanf, it's the best method for your situation. Here's the documentation for scanf, pay particular attention to the "Return Value" section: scanf(3) - Linux manual page.
    Last edited by anduril462; 03-12-2011 at 08:45 PM.

  9. #9
    Registered User
    Join Date
    Mar 2011
    Location
    Baltimore Md. USA
    Posts
    58
    The article seems to be pointing to EOF, if that is correct here is my updated while loop. I'll keep looking into fscanf.
    Code:
    while (fscanf(spData, "%d", &score) != EOF) 
       {
    
            if (score > 90)
            { fprintf(spGradelist, "%d", score);//creates new file
    			count++;}
            else
                {below++;}
    still it compiles but does't open the file.

    also forget the //creates new file. I forgot to erase that.

  10. #10
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    but does't open the file.
    So you mean you're seeing:
    printf("Could not open file \a\n");
    Because if you aren't, then it is opening the file. And if it's not opening the file (because you are seeing that message) then your file doesn't exist or you don't have permissions to open it, etc. None of which has anything to do with your loop.


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

  11. #11
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,909
    Are you sure it's not opening the file? Why do you think that?

    You really should be checking the return value of both fopen calls. If either one fails, you should print out an error saying which one failed and why. Look into errno, strerror and perror for printing out why it failed. It may be something like a permissions issue if it's actually not opening the file. There's nothing wrong with your fopen calls from a C point of view.

    If you are simply not getting the desired output, it's probably your fscanf call. The scanf functions are picky. You need to scan the name before you can scan the integer. Try something like "%*s%d" for your fscanf string. The * means don't store the string, just read it. If scanf correctly read a score, it should return 1 (one value scanned successfully). Make your loop run while fscanf keeps returning 1. Then, if it fails, you can check why it failed:
    Code:
    while (fscanf(spData, "%*s%d", &score) == 1) {
    }
    if (!feof(spData)) {
        // Error! fscanf stopped, but not due to EOF.  Print something useful!
    }
    Lastly, you need to print spaces between numbers in your output file so if you go to read them back it, you can distinguish the numbers.

  12. #12
    Registered User
    Join Date
    Mar 2011
    Location
    Baltimore Md. USA
    Posts
    58
    here is updated code, it compiles but gives error message "could not open textfile1". I'll have to look into it tomorrow. I must have done something wrong. We just started reading and writing files this week, so I'm sure I am missing something.
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    FILE* spData;// file to read from
    FILE* spGradelist;
    
    int main()//main
    {
    
    int below = 0; //local declarations
    int count = 0;
    int score;
    
     printf("This program will print scores over 90%%\n");
    
    spGradelist = fopen("Gradelist.txt", "w");
    spData = fopen("TextFile1.txt", "r");
        if (!spData)
            {
            printf("Could not open file Textfile1 \a\n");
            exit (101);
            }//if open fails
            
    while (fscanf(spData, "%*s%d", &score) == 1) {
    
    if (!feof(spData)) {
        printf("Error! fscanf stopped, but not due to EOF\n");
    }
    
            if (score > 90)
            { fprintf(spGradelist, "%d", score);
    			count++;}
            else
                {below++;}
    }
    printf("The number of scores above 90%% are %d\n", count);
    printf("The number of scores below 90%% are %d\n", below);
    
    
    
    fclose(spData);
    fclose(spGradelist);
    return 0;
    }//main
    I also fixed the space in my fprintf line, thanks for all of your insight. I appreciate it a lot.

  13. #13
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    If it fails to open the file, then you can ignore everything else in your code from that point on. The problem is that the file you are trying to access either doesn't exist, or you don't have permission to access it. (Or in the case of writing a new one, you can't create a new file there for some reason.)


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

  14. #14
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Quote Originally Posted by time4f5 View Post
    here is updated code, it compiles but gives error message "could not open textfile1". I'll have to look into it tomorrow. I must have done something wrong. We just started reading and writing files this week, so I'm sure I am missing something.
    Most likely it just can't find the file. Oddly enough, the matter that you get the error report from fopen() and not the compiler or operating system tells you it's working and working correctly...

    You are specifying only the file name to be opened, so that file must exist in the same folder as your program executable file. If you are working with an IDE that creates separate folders for debug and distro copies of your program, you will have to place copies of the file in each of those folders.

    Alternatively you could specify a fully qualified path to the file.
    For example: "C:\\testfiles\\assignment\\textfile1.txt" (for Windows systems)

  15. #15
    Registered User
    Join Date
    Mar 2011
    Location
    Baltimore Md. USA
    Posts
    58
    Ok. I have it narrowed down to the file attachment process. I have googled the process to no avail. Here is what I did, if you see something wrong with my process, please let me know. I use Visual Studio 2010 professional Edition C++. I selected new, then file. In the file box I selected text file. once I opened it up and put the information into it, I saved it. Then I selected project, add it to existing. and it shows up under my project box on the left side off the screen below my source code.

    If this is the correct process then maybe there is something in my settings that I need to adjust. any insight on that would be helpful as well. thanks.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. reading and writing to a binary file
    By greg677 in forum C Programming
    Replies: 2
    Last Post: 05-24-2010, 08:09 PM
  2. Problems installing Mingw5.1.4
    By BlackOps in forum C Programming
    Replies: 2
    Last Post: 07-26-2009, 03:28 AM
  3. Replies: 3
    Last Post: 03-04-2005, 02:46 PM
  4. file writing and reading
    By Micko in forum C Programming
    Replies: 8
    Last Post: 01-13-2004, 11:18 AM
  5. what does this mean to you?
    By pkananen in forum C++ Programming
    Replies: 8
    Last Post: 02-04-2002, 03:58 PM