Thread: Need Help with fscanf, a bit confused

  1. #1
    Registered User
    Join Date
    Nov 2017
    Posts
    3

    Need Help with fscanf, a bit confused

    I just started doing programming, and have been trying to self-learn and i have hit some obstacles. Maybe someone can help?

    In data in/out onto a text file;
    To put something onto a text file, I know, we can use fprintf; For example, if i want to open a file named test, and want to put "hello hi" into it, I can use the following code:

    Code:
    #include <stdio.h>
    int main()
    {
        FILE *myfile;
        myfile=fopen("test.txt", "w");
        fprintf(myfile, "Hello Hi \n");
        fclose (myfile);
        
        return 0;
    }
    But, what if I wanted the user to input something, then i put that something in the text file. For example: I ask the user for his name, he inputs: "John Deere". How do i put "John Deere" into the text file?

    I would really appreciate the help, if anyone can write me a simple code for that scenario. Thanks a lot in advance.

  2. #2
    Registered User rstanley's Avatar
    Join Date
    Jun 2014
    Location
    New York, NY
    Posts
    1,106
    Here is one possible way with a few improvements.
    Code:
    #include <stdio.h>
    
    #define DIM 512
    
    int main()
    {
       FILE *myfile = NULL;  // Initialize all local variables.
       char buff[DIM]= "";
    
       myfile=fopen("test.txt", "w");
       if(myfile == NULL)   // Always test if the file was opened
       {
          printf("File open failed! Exiting.");
          return 1;  // EXIT_FAILURE in stdlib.h is better
       }
    
       printf("Please enter a name: ");
       fgets(buff, DIM, stdin);
    
       fprintf(myfile, "%s\n", buff);
    
       fclose (myfile);
    
       return 0;  // EXIT_SUCCESS here as well
    }
    Last edited by rstanley; 11-01-2017 at 07:52 AM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. fscanf help
    By Lexi Anderson in forum C Programming
    Replies: 7
    Last Post: 03-31-2014, 09:16 PM
  2. Need help with fscanf
    By dford425 in forum C Programming
    Replies: 8
    Last Post: 01-16-2011, 06:44 PM
  3. fscanf()
    By Maz in forum C Programming
    Replies: 15
    Last Post: 08-31-2009, 08:30 AM
  4. fscanf
    By mesmer in forum C Programming
    Replies: 5
    Last Post: 11-09-2008, 10:34 AM
  5. fscanf on sun's
    By brif in forum C Programming
    Replies: 2
    Last Post: 04-14-2002, 01:22 PM

Tags for this Thread