Thread: Problems opening a file for read only

  1. #1
    Registered User
    Join Date
    Feb 2013
    Posts
    41

    Problems opening a file for read only

    Hi Guys, I've checked around on past posts, web and my book but am unable to grasp how to open a file and just print what is in that file on the screen. I though maybe I had the directory wrong but putting G:\\ or G: give me the same result. If you guys can easily see what I am doing wrong any help would be appreciated. When I select 1 it just goes to the next line and doesn't print anything.
    Code:
    int getchoice(void)
    
     {
    
    int num;
    
    int choice;
    
    FILE* outputfile;
    
    do
    
        {
    
            printf("   Menu\n");
    
            printf("<1>Read data from a file\n");
    
            printf("<2>Read data interactively\n");
    
            printf("   Enter choice:\n");
    
            scanf("%d",&choice);
    
    
    switch(choice)
    
             {
    
    case 1: outputfile = fopen("g:output.txt", "r");
    
    while(fscanf(outputfile, "&d", &num) != EOF);
    
                         {
    
                            printf("%d", num);
    
                         }
    
                         fclose(outputfile);
    
    return 0;
    
    break;
    
    case 2: school();
    
    break;
    
    default: printf("Press enter a valid selection\n");
    
             }
    
    
             
    
        } while(choice !=3);
    
    
     }  


  2. #2
    Registered User
    Join Date
    Feb 2013
    Posts
    41
    Anyone know a good place to look for some more info on this? I'm not sure what else to try. Thanks again

  3. #3
    Registered User
    Join Date
    May 2009
    Posts
    4,183
    Code:
    while(fscanf(outputfile, "&d", &num) != EOF);
    The semi colon at the end of the above line is a problem.
    Try removing it.

    Edit: I also prefer "== 1" or "> 0" instead of "!= EOF".

    Tim S.
    "...a computer is a stupid machine with the ability to do incredibly smart things, while computer programmers are smart people with the ability to do incredibly stupid things. They are,in short, a perfect match.." Bill Bryson

  4. #4
    Registered User
    Join Date
    Feb 2013
    Posts
    41
    Thank you I removed the ; and it ran but when I tried removing the !=EOF it would just crash. The problem with it running is it prints out garage (-858993460) and not the number I've typed into the txt file. Thanks again.

  5. #5
    Registered User
    Join Date
    Jun 2005
    Posts
    6,815
    Tim did not suggest removing the !=EOF. He suggested replacing it with something else.

    It would probably also be a good idea to check that the fopen() call succeeded, before attempting to read from the file.
    Right 98% of the time, and don't care about the other 3%.

    If I seem grumpy or unhelpful in reply to you, or tell you you need to demonstrate more effort before you can expect help, it is likely you deserve it. Suck it up, Buttercup, and read this, this, and this before posting again.

  6. #6
    Registered User
    Join Date
    Feb 2013
    Posts
    41
    Sorry about that I didnt mean I just removed it I replaced it with the code below and it gives me this error: The program '[1212] ConsoleApplication2.exe' has exited with code 0 (0x0). I'm sure I'm doing something stupid but from the examples I keep seeing its just not clicking. Current code
    Code:
     
    case
     
     
     
     1: outputfile = fopen("g:\\output.txt", "r");
    
    
     
                
     
     
    while(fscanf(outputfile, "&d", &num) > 1)
    
    
     
                         {
    
     
                            
    
     
                            
    
     
                            printf(
     
     
    "%d", num);
    
    
     
                         }
    
    
     
                            fclose(outputfile);
    
    
     
                                
     
     
    return 0;
    
    
     
                                
     
     
    break;


    Last edited by phillyflyers; 04-04-2013 at 09:55 PM. Reason: Not sure why the format is all crazy this time

  7. #7
    Registered User
    Join Date
    Jun 2005
    Posts
    6,815
    That behaviour you describe is exactly correct, based on the code (noting you used something different than Tim suggested).

    fscanf() will only return a value greater than one if it reads two or more values. Since you're telling it to read only one value, it will never return a value that exceeds 1. That while loop will terminate the first time through, without ever calling printf().
    Right 98% of the time, and don't care about the other 3%.

    If I seem grumpy or unhelpful in reply to you, or tell you you need to demonstrate more effort before you can expect help, it is likely you deserve it. Suck it up, Buttercup, and read this, this, and this before posting again.

  8. #8
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,662
    > Last edited by phillyflyers; 52 Minutes Ago at 04:55 AM. Reason: Not sure why the format is all crazy this time
    Try using "paste as text" when you copy/paste from your IDE.
    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.

  9. #9
    Registered User
    Join Date
    Feb 2013
    Posts
    41
    Ok I've changed it to ==1 so shouldnt that mean as long as there is something on that line it will print it? When I do this again nothing comes out and I cant really figure out how to tell it to print everything in the file I thought I was doing that under the printf command. I also changed it to char but that made no difference
    Code:
    int getchoice(void)
    
     {
    
    char num;
    
    int choice;
    
    FILE* outputfile;
    
    do
    
        {
    
            printf("   Menu\n");
    
            printf("<1>Read data from a file\n");
    
            printf("<2>Read data interactively\n");
    
            printf("   Enter choice:\n");
    
            scanf("%d",&choice);
    
    
    switch(choice)
    
             {
    
    case 1: outputfile = fopen("c:\\output.txt", "r");
    
    while(fscanf(outputfile, "&c", &num) == 1);
    
                         {
    
                            printf("%c", num);
    
                         }
    
                         fclose(outputfile);
    
    return 0;
    
    break;
    
    case 2: school();
    
    break;
    
    default: printf("Press enter a valid selection\n");
    
             }
    
    
             
    
        } while(choice <=2);
    
    
     }  

  10. #10
    Registered User
    Join Date
    May 2012
    Posts
    1,066
    Code:
    case 1: outputfile = fopen("c:\\output.txt", "r");
    Check the return value of fopen(). Is your file really in the root directory? (Is that even a valid path in Windows?)

    You could also assign the return value of fscanf() to a variable and check its value.

    [Edit]And please paste your code as plain text[/Edit]

    Bye, Andreas

  11. #11
    Registered User
    Join Date
    May 2009
    Posts
    4,183
    Do you want your printf to ONLY print the last char in the file?
    If not, fix the code; I told you how in my first post.

    Why do you still have the semi-colon; and when did the "&c" appear instead of "%c" in the fscanf?

    Edit: Looks like I missed the "&d" in the original code; you really need a good compiler with warning turned way up.

    Tim S.

    Code:
    while(fscanf(outputfile, "&c", &num) == 1);
    
                         {
    
                            printf("%c", num);
    
                         }
    "...a computer is a stupid machine with the ability to do incredibly smart things, while computer programmers are smart people with the ability to do incredibly stupid things. They are,in short, a perfect match.." Bill Bryson

  12. #12
    Registered User
    Join Date
    May 2009
    Posts
    4,183
    Your code reformatted and with added comments.

    Code:
    #include <stdio.h>
    
    void school(void);
    
    int getchoice(void)
    {
        char num;
        int choice;
        FILE* outputfile;
    
        do {
    
            printf("   Menu\n");
            printf("<1>Read data from a file\n");
            printf("<2>Read data interactively\n");
            printf("   Enter choice:\n");
    
            scanf("%d", &choice);
    
            switch(choice) {
    
            case 1:
                outputfile = fopen("c:\\output.txt", "r");
    
                while(fscanf(outputfile, "&c", &num) == 1);
    
                /* The printf below is NOT part of the while above
                   because of the trailing semicolon after the while.
                */
    
                {
    
                    printf("%c", num);
    
                }
    
                fclose(outputfile);
    
                return 0;
    
                break;
    
            case 2:
                school();
    
                break;
    
            default:
                printf("Press enter a valid selection\n");
    
            } // end switch
        } while(choice <= 2);
    } // end getchoice()
    Meaningful warnings I got below; removed the linker errors because it is missing the rest of your program.
    Tim S.

    Code:
    mingw32-gcc.exe -Wall  -g  -Wmissing-include-dirs    -c C:\Users\stahta01\Downloads\interfaces\testc\main.c -o obj\Debug\main.o
    C:\Users\stahta01\Downloads\interfaces\testc\main.c: In function 'getchoice':
    C:\Users\stahta01\Downloads\interfaces\testc\main.c:25:13: warning: too many arguments for format [-Wformat-extra-args]
    C:\Users\stahta01\Downloads\interfaces\testc\main.c:53:1: warning: control reaches end of non-void function [-Wreturn-type]
    "...a computer is a stupid machine with the ability to do incredibly smart things, while computer programmers are smart people with the ability to do incredibly stupid things. They are,in short, a perfect match.." Bill Bryson

  13. #13
    Registered User
    Join Date
    Feb 2013
    Posts
    41
    Hi stahta01 thanks again, My apologies on putting back the trailing semi colon was a typo. I changed some things around and with your help and everyone else we finally got the program running!!!!

    Thank you all for such patience and this community is really great and helpful. I have one last thing I need to do before I finish and its about the print format. In the file I open I have 3 number per row for 2 rows.
    So something like 21 34 21
    23 43 12.
    The program prints them out in a striaght line. I've been googling some keywords to try to see how to do this but I must be wording it wrong. Can you guys give me a tip on what to search for I feel bad asking for any more help on something that I'm sure we have covered and I have forgotten lol.

    I have posted the code to see it works ! I should of done that to start with. Thanks again everyone!
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <math.h>
    
    // function declarations
    float schoolgrade(float x, float y, float z); // this will do the calculations
    float useroutput(float CG, float HG, float MG, float FG); //this will print the ouput to the user
    float school ();
    int getchoice ();
    int main ()
    {
     int choice; // local declarations
     
     choice = getchoice();
    }
    
    float school ()
    {
     float homework = 0;
     float midterm = 0;
     float finalexam = 0;
     float finalgrade = 0;
     int student = 0;
     int studentID = 1;
     
     printf("Enter total number of students \n");
     scanf("%d" ,&student);
     
     while(student > 0) 
     {
     printf ("Enter 3 grades for student %d\n", studentID);
     scanf  ("%f %f %f",&finalexam, &midterm, &homework);
      if (finalexam <= 100 && finalexam >= 0 && midterm <= 75 && midterm >= 0 && homework  <= 120 && homework >= 0)
       {
       finalgrade = schoolgrade(finalexam, midterm, homework);
       useroutput(finalexam, midterm, homework, finalgrade);
       system ("pause");
       student--;
       studentID++;
       }
      else
      {
      printf("Incorrect value entered \n");
      }
     }
     
    }
     
    
    float schoolgrade(float x, float y, float z)
    {
    float CG = 0;
    float HG = 0;
    float MG = 0;
    float FG = 0;
     
      FG = (x/100) * .30;  
      MG = (y/75) * .20;
      HG = (z/120) * .50;
       
       
    CG = (FG + MG + HG) * 100;
    return CG;
    
    }
    
    float useroutput(float a, float b, float c, float d)
    {
     printf ("Final exam was %.f out of 100 \n", a);
     printf ("Medterm exam was %.f out of 75 \n", b);
     printf ("Homework assignments were %.f out of 120 \n ",c);
       puts ("---------------------------------------- \n");
     printf ("Grade is %.f \n", d);
    }
    int getchoice(void)
     {
    int num;
    int choice;
    FILE* outputfile;
    FILE* inputfile;
    do
        {
            printf("   Menu\n");
      printf("<1>Read data from a file\n");
      printf("<2>Read data interactively\n");
      printf("   Enter choice:\n");
      scanf("%d",&choice);
    
      switch(choice)
             {
       case 1: outputfile = fopen("G:\\output.txt", "r");
       while(fscanf(outputfile, "%d", &num) == 1 )
                         {
          
          
                            printf("%3d\n", num);
          
          
                         }
          fclose(outputfile);
           return 0;
           break;
        case 2: school();
         break;
        default: printf("Press enter a valid selection\n");
             }
     } while(choice <=2);
    
     }
    PS sorry about the weird formatting, I have been using visual studio express so to get it in plain text I just pasted into a note pad first.






Popular pages Recent additions subscribe to a feed

Similar Threads

  1. opening a file to read
    By surfingbum18 in forum C Programming
    Replies: 3
    Last Post: 11-08-2007, 02:05 PM
  2. Problems in opening a txt file in a loop
    By anilk in forum C Programming
    Replies: 1
    Last Post: 02-05-2006, 03:35 AM
  3. Problems opening file
    By Ganoosh in forum C++ Programming
    Replies: 6
    Last Post: 08-30-2005, 01:29 PM
  4. problems with opening a file from a string
    By acidbeat311 in forum C Programming
    Replies: 6
    Last Post: 04-22-2005, 10:58 AM
  5. read from file problems
    By paperbox005 in forum C++ Programming
    Replies: 6
    Last Post: 10-09-2004, 09:55 AM