Creating a file with random numbers question??

This is a discussion on Creating a file with random numbers question?? within the C Programming forums, part of the General Programming Boards category; Here goes: Code: #include <ctype.h> #include <stdio.h> #include <stdlib.h> #include <string.h> void get_info(char *filename, int *n_ptr); FILE *cfopen(char *filename, char ...

  1. #16
    Registered User
    Join Date
    Feb 2006
    Location
    North Liberty, IA
    Posts
    67
    Here goes:

    Code:
    #include <ctype.h>
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    void get_info(char *filename, int *n_ptr);
    
    FILE *cfopen(char *filename, char *mode);
    
    FILE *gfopen(char *filename, char *mode);
    
    int main(void)
    {
         FILE  *ofp;
         int     i,n=0;
         char  filename[120];
    
         get_info(filename, &n);
         ofp = cfopen(filename, "r+");
    
          for(i=1; i<=n; ++i){
               fprintf(ofp, "%12d", rand());
               if(i%6 == 0 || i == n)
                  fprintf(ofp, "\n");
         }
    }
    
    void get_info(char *filename, int *n_ptr)
    {
        prinf("\n%s\n\n%s",
    	"This progam creates a file of random numbers.",
    	"How many random numbers would you like?   ");
        scanf("%d", n_ptr);
        printf("\nIn what file would you like them?  ");
        scanf("%s", filename);
    }
    
    
    
    
    FILE *cfopen(char *filename, char *mode)
    {
        char  reply[2];
        FILE  *fp;
     
        if(strcmp(mode, "w") == 0
          && (fp = fopen(filename, "r")) != NULL){
            fclose(fp);
    	printf("\nFile exists.  Overwrite it? ");
            scanf("%1s", reply);
            if(*reply != 'y' && *reply != 'Y') {
            printf("\nBye!\n\n");
    	exit(1);
    	}
          fp = gfopen(filename, mode);
          return fp;
    }
    
    
    
    FILE *gfopen(char *filename, char *mode)
    {
        FILE *fp;
        
        if((fp = fopen(filename,mode)) == NULL){
        fprintf(stderr, "Cannot open %s - bye!\n", filename);   
        exit(1);
        }
        return fp;
    }

  2. #17
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,046
    Code:
    scanf("%s", filename);
    You might want to use fgets().
    Code:
    scanf("%1s", reply);
    You might want to use fgets() or getchar() here.

    And you should close the file:
    Code:
    fclose(ofp);
    Other than that (and the lack of consts), it's a good program. Congrats.
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

  3. #18
    Registered User
    Join Date
    Mar 2005
    Posts
    140
    Sorry, I meant unbalanced brace in function cfopen.
    I'm not sure what your trying to do, but this is what it looks like with more consistent indentation
    Code:
    FILE *cfopen(char *filename, char *mode)
    {
        char  reply[2];
        FILE  *fp;
    
        if(strcmp(mode, "w") == 0 && (fp = fopen(filename, "r")) != NULL)
        {  // '{' <--- never closed
            fclose(fp);
            printf("\nFile exists.  Overwrite it? ");
            scanf("%1s", reply);
    
            if(*reply != 'y' && *reply != 'Y')
            {
                printf("\nBye!\n\n");
                exit(1);
            }
    
        fp = gfopen(filename, mode);
        return fp;
    }
    You still have a prinf instead of printf in get_info

  4. #19
    Registered User
    Join Date
    Feb 2006
    Location
    North Liberty, IA
    Posts
    67
    Thanks to both of you guys. 1. I can understand better how to actally call the function correctly. 2. I can see how the filename is passed around correctly.

    Thanks again.

  5. #20
    Registered User
    Join Date
    Feb 2006
    Location
    North Liberty, IA
    Posts
    67
    Hey guys. I have visualstudio.net as to write my code on. When I run this code, it doesn't let me enter the file. It just comes up with an error message that says that it can't find the specified file.
    It's interactive though. It's suppose to ask me what file to put the random numbers in. Any suggestions?


    Code:
    #include <ctype.h>
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    void get_info(char *filename, int *n_ptr);
    
    FILE *cfopen(char *filename, char *mode);
    
    FILE *gfopen(char *filename, char *mode);
    
    int main(void)
    {
         FILE  *ofp;
         int     i,n=0;
         char  filename[120];
    
         get_info(filename, &n);
         ofp = cfopen(filename, "r+");
    
          for(i=1; i<=n; ++i){
               fprintf(ofp, "%12d", rand());
               if(i%6 == 0 || i == n)
                  fprintf(ofp, "\n");
         }
         fclose(ofp);
    }
    
    void get_info(char *filename, int *n_ptr)
    {
        printf("\n%s\n\n%s",
    	"This progam creates a file of random numbers.",
    	"How many random numbers would you like?   ");
        scanf("%d", n_ptr);
        printf("\nIn what file would you like them?  ");
        scanf("%s", filename);
    }
    
    
    
    
    FILE *cfopen(char *filename, char *mode)
    {
        char  reply[2];
        FILE  *fp;
     
        if(strcmp(mode, "w") == 0
          && (fp = fopen(filename, "r")) != NULL){
            fclose(fp);
    	printf("\nFile exists.  Overwrite it? ");
            scanf("%1s", reply);
            if(*reply != 'y' && *reply != 'Y') {
            printf("\nBye!\n\n");
    	exit(1);
    	}
          fp = gfopen(filename, mode);
          return fp;
    }
    
    
    
    FILE *gfopen(char *filename, char *mode)
    {
        FILE *fp;
        
        if((fp = fopen(filename,mode)) == NULL){
        fprintf(stderr, "Cannot open %s - bye!\n", filename);   
        exit(1);
        }
        return fp;
    }
    Last edited by Hoser83; 02-15-2006 at 03:56 PM.

  6. #21
    The Richness... Richie T's Avatar
    Join Date
    Jan 2006
    Location
    Ireland
    Posts
    469
    that code still doesn't compile, missing brace before function
    gfopen. the problem is with cfopen, i'm sorry to say that the code
    for that function is so restrictive, it's really shoddy work, and i
    know that's not your fault, you didn't write it. i would take it up
    with whoever did write it, because the only way i can get your
    program to work is by calling cfopen with "w" instead, AND that
    the destination file exists already. as it stands now, cfopen just
    won't cut it.

    also if its skipping over the part where it's supposed to read in
    a file name (this didn't happen for me but i'm on a different
    compiler), you'll need to flush the input buffer.

    http://faq.cprogramming.com/cgi-bin/...&id=1043284392
    No No's:
    fflush (stdin); gets (); void main ();


    Goodies:
    Example of fgets (); The FAQ, C/C++ Reference


    My Gear:
    OS - Windows XP
    IDE - MS Visual C++ 2008 Express Edition


    ASCII stupid question, get a stupid ANSI

  7. #22
    Registered User
    Join Date
    Feb 2006
    Location
    North Liberty, IA
    Posts
    67
    okay, I got it so it will run, but my file will not open no matter what I put in there. Is this because of my cfopen function?
    This is the first time I've ever done this so I don't know what to expect. Does it write to the file, and we don't see any of it. How do we know if the program was successful?
    Last edited by Hoser83; 02-15-2006 at 04:10 PM.

  8. #23
    The Richness... Richie T's Avatar
    Join Date
    Jan 2006
    Location
    Ireland
    Posts
    469
    ya thats kind of what i was getting at, the code for cfopen is
    bad, you need to change

    ofp = cfopen(filename, "r+");

    to this

    ofp = cfopen(filename, "w");

    now go to what ever directory you are running the executable
    from (wherever you/your compiler has it saved) and create a text
    document using notepad called "h.txt". you don't need to put
    anything in it, but the file extension is important so yo can view it
    using notepad (i'm totally assuming you're on windows).
    now run the modified code, and for the file name type h.txt.

    what that does for me is writes the random numbers into the file
    h.txt. thats the only way that the code as it stands at the
    moment i think. try what i have said exactly and get back to me
    on it. also to answer what you asked, it won't display the values
    written to the file on screen, so open the file and you will
    see them there
    No No's:
    fflush (stdin); gets (); void main ();


    Goodies:
    Example of fgets (); The FAQ, C/C++ Reference


    My Gear:
    OS - Windows XP
    IDE - MS Visual C++ 2008 Express Edition


    ASCII stupid question, get a stupid ANSI

  9. #24
    Registered User
    Join Date
    Feb 2006
    Location
    North Liberty, IA
    Posts
    67
    Yeah, I got it to work that way. Thanks. Hey Richie if you have time to look at this one last thing. It's the same program with some modifications I made so that if you input something like 46i instead of 461, it causes an error. I can get it to tell me there is an error and to write to a file, but I don't think it gives me the right number of random numbers. Can you run it and see what you come up with. Thanks man. Am I printing them out right in my for loop?


    Code:
    #include <ctype.h>
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    #define MAXLINE   100
    
    FILE *cfopen(char *filename, char *mode);
    
    FILE *gfopen(char *filename, char *mode);
    
    int main(void)
    {
         FILE  *ofp;
         int     i; 
         char  filename[120],*pEnd ,line[MAXLINE];
         
            
    
        printf("\n%S\n\n%s",
    	"This progam creates a file of random numbers.",
    	"Please enter in the number of random numbers you would like to see as a positive integer.   "),
        
    	fgets( line, MAXLINE, stdin);
        
        if((strtol(line, &pEnd, 0)) <= 0 || *pEnd != '\n')
             {
                printf("\nERROR: Please enter positive integer.\n");
             }
        
         printf("\nIn what file would you like them?  ");
         scanf("%s", filename);
    
         ofp = cfopen(filename, "w");
    
          
            
            for(i=1; i<=(int)line; ++i){
               fprintf(ofp, "%12d", rand());
               if(i%6 == 0 || i == (int)line)
                  fprintf(ofp, "\n");
         }
    }
    
    
    
    
    
    FILE *cfopen(char *filename, char *mode)
    {
        char  reply[2];
        FILE  *fp;
     
        if(strcmp(mode, "w") == 0
          && (fp = fopen(filename, "r")) != NULL){
    		  fclose(fp);}
    	printf("\nFile exists.  Overwrite it? ");
            scanf("%1s", reply);
            if(*reply != 'y' && *reply != 'Y') {
            printf("\nBye!\n\n");
    	exit(1);
    	}
          fp = gfopen(filename, mode);
          return fp;
    }
    
    
    
    FILE *gfopen(char *filename, char *mode)
    {
        FILE *fp;
        
        if((fp = fopen(filename,mode)) == NULL){
        fprintf(stderr, "Cannot open %s - bye!\n", filename);   
        exit(1);
        }
        return fp;
    }

  10. #25
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Read one of the various FAQs on getting input from a user, and pick a different method.


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

  11. #26
    Registered User
    Join Date
    Feb 2006
    Location
    North Liberty, IA
    Posts
    67
    I totally agree with you quzah, but this is what I have to use. The only thing I have left to figure out is how to print the correct number of random numbers into the file using my for loop and using line prints to many which makes sense to me now.
    Last edited by Hoser83; 02-15-2006 at 05:25 PM.

  12. #27
    The Richness... Richie T's Avatar
    Join Date
    Jan 2006
    Location
    Ireland
    Posts
    469
    ok what i have discovered is that your validation doesn't change
    the entered value back to an int. you may not know this,
    but when you read in a string, the numerical values 0-9 are stored
    as their ascii values, which do not run from 0-9. ascii character 0
    is the decimal value 48, 1 is 49 and so on. check it out with this:

    printf ("%c", 48);

    so when you casted the value in your loop, you are casting to this
    value, well actually you were dealing with the memory address,
    in the lool, line was supposed to be *line.

    look up atoi. i have to go now, sorry i couldnt help more at the
    moment
    No No's:
    fflush (stdin); gets (); void main ();


    Goodies:
    Example of fgets (); The FAQ, C/C++ Reference


    My Gear:
    OS - Windows XP
    IDE - MS Visual C++ 2008 Express Edition


    ASCII stupid question, get a stupid ANSI

  13. #28
    Registered User
    Join Date
    Mar 2005
    Posts
    140
    Code:
    int main(void)
    {
        FILE  *ofp;
        int   i;
        long  input;
        char  filename[120],*pEnd ,line[MAXLINE];
    
        printf("\n%S\n\n%s",  // Why is this still a capital S
            "This progam creates a file of random numbers.",
            "Please enter in the number of random numbers you would like to see as a positive integer.   "),
    
        fgets( line, MAXLINE, stdin);
    
        //Store result of strtol in a long int, instead of doing additional conversion later
        if((input = strtol(line, &pEnd, 0)) <= 0 || *pEnd != '\n')
        {
            printf("\nERROR: Please enter positive integer.\n");
            //since something bad happened... exit (or loop back to try again)
            exit(1);
        }
    
        printf("\nIn what file would you like them?  ");
        scanf("%s", filename);
    
        ofp = cfopen(filename, "w");
    
        for(i=1; i <= input; ++i)
        {
            fprintf(ofp, "%12d", rand());
            if(i%6 == 0 || i == input)
            {
                fprintf(ofp, "\n");
            }
        }
    
        //CLOSE THE FILE
        //RETURN 0
    }
    
    FILE *cfopen(char *filename, char *mode)
    {
        char  reply[2];
        FILE  *fp;
    
        if(strcmp(mode, "w") == 0 && (fp = fopen(filename, "r")) != NULL)
        {
              fclose(fp);
        }
    
        //I doubt this is what you want... always assume the file already exists?
        printf("\nFile exists.  Overwrite it? ");
    
        scanf("%1s", reply);
        if(*reply != 'y' && *reply != 'Y')
        {
            printf("\nBye!\n\n");
            exit(1);
        }
    
        fp = gfopen(filename, mode);
        return fp;
    }
    Last edited by spydoor; 02-16-2006 at 12:38 PM.

  14. #29
    Registered User
    Join Date
    Feb 2006
    Location
    North Liberty, IA
    Posts
    67
    Thanks a bunch guys. After looking at it for quite awhile last night, I was able to make it work the same way spydoor has it set up. I was going to post that I had it working, but when I was done, I basically colapsed in my chair. Thanks a lot for the help though. I REALLY appreciate it.

Page 2 of 2 FirstFirst 12
Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Creating File Handling Functions
    By td4nos in forum C Programming
    Replies: 6
    Last Post: 06-26-2009, 11:43 AM
  2. gcc link external library
    By spank in forum C Programming
    Replies: 6
    Last Post: 08-08-2007, 03:44 PM
  3. C++ std routines
    By siavoshkc in forum C++ Programming
    Replies: 33
    Last Post: 07-28-2006, 12:13 AM
  4. Replies: 4
    Last Post: 11-16-2004, 06:29 AM
  5. archive format
    By Nor in forum A Brief History of Cprogramming.com
    Replies: 0
    Last Post: 08-05-2003, 07:01 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21