Thread: Help: Reading and writing to a file. Program Error.

  1. #1
    Registered User
    Join Date
    May 2011
    Posts
    1

    Help: Reading and writing to a file. Program Error.

    I am trying to write a basic program that will take a number from a file; perform a sequence and write it back to the file. The program runs and works, but everytime I run it; a window says "...has encountered a problem and needs to close...". Is there something wrong with my code?


    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    int main()
    {
    
        /*  Declare integer.  Open File  */
    
        int n;
        FILE * infile;
        infile=fopen("myfile.txt", "r");
    
    
        /*  ERROR IN FILE  */
    
        if(infile==NULL){
            printf("Your file does not exist\n");
            return -1;}
    
    
        /*  Scan integer from file.  Close File  */
    
        fscanf(infile, "%d", &n);
        fclose(infile);
    
    
        /*  Open file again. Write to file  */
    
        infile=fopen("myfile.txt", "a");
    
    
        while(n>1){
            if((n%2)==0){
            n=n/2;
            fprintf(infile, " %d", n);
            if(n==1){goto done;}
            }
    
            if((n%2)==1){
            n=(3*n)+1;
            fprintf(infile, " %d", n);
            if(n==1){goto done;}
            }
    
        }
    
        done:
        fclose("infile");
        printf("DONE.  Check the file");
    
        return 0;
    }

  2. #2
    Registered User
    Join Date
    Apr 2011
    Location
    Las Vegas
    Posts
    66
    fclose needs to be passed the FILE, not a string, e.g.
    Code:
    fclose(infile);
    Kevin

  3. #3
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Also...
    Code:
    int main( void )
    Code:
            if((n%2)==0){
            }
            else{
            }
    Code:
            if((n%2)==0){
            ...
            if(n==1){ break;}
            }
            ...
            if(n==1){ break;}
            }

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

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. File reading and writing
    By Noobwaker in forum C Programming
    Replies: 6
    Last Post: 03-08-2006, 02:28 AM
  2. Reading & Writing files (Error)
    By Blackroot in forum C++ Programming
    Replies: 9
    Last Post: 01-10-2006, 11:55 AM
  3. File editing - error reading/writing %
    By Tankndozer in forum C Programming
    Replies: 3
    Last Post: 07-05-2004, 11:14 AM
  4. reading & writing to a file
    By Micko in forum C++ Programming
    Replies: 5
    Last Post: 05-08-2004, 11:57 AM
  5. File reading and writing
    By GaPe in forum C Programming
    Replies: 28
    Last Post: 12-31-2001, 01:34 PM