Thread: program to write string to file

  1. #1
    Registered User
    Join Date
    Jul 2016
    Posts
    7

    program to write string to file

    Hi I am trying to create code to receive input from a user and write it to a file. It is not compiling properly, some error concerning main pops up. what am I doing wrong?


    Code:
    #include<stdio.h>
    #include <stdlib.h>
    
    
    int main() {
     FILE *fil;
     int c;
     
     fil=fopen("new.txt", "w");
     if(fil==NULL){
         printf("error");
         exit(1);
     }
     printf("Enter some words\n");
     scanf("%d", &c);
     
     fprintf(fil, "%d", c);
     fclose(fil);
     return 0;
    }

  2. #2
    Registered User rstanley's Avatar
    Join Date
    Jun 2014
    Location
    New York, NY
    Posts
    1,127
    Code:
    scanf("%d", &c);
    %d is the format specifier for entering an integer.

    The following is a standard way to input a string:
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    #define DIM 256
    
    int main(void) {
       FILE *fil;
       //   int c;
       char buffer[256] = "";
    
       fil=fopen("new.txt", "w");
    
       if(fil==NULL){
          printf("error");
          exit(1);
       }
    
       printf("Enter some words\n");
    
       // scanf("%d", &c);
       fgets(buffer, DIM, stdin);
    
       // fprintf(fil, "%d", c);
       fprintf(fil, "%s", buffer);
    
       fclose(fil);
       return 0;
    }

  3. #3
    Registered User
    Join Date
    Jul 2016
    Posts
    7
    Thanks so much its works now . Im so glad I was wondering what was wrong. Have a blessed day

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 2
    Last Post: 08-30-2014, 11:07 PM
  2. Replies: 1
    Last Post: 02-22-2012, 03:52 PM
  3. Receives string from keyboard and write to a file
    By georgio17 in forum C Programming
    Replies: 2
    Last Post: 04-16-2011, 08:30 AM
  4. Replies: 2
    Last Post: 03-04-2010, 04:19 AM
  5. Replies: 14
    Last Post: 01-18-2008, 04:14 PM

Tags for this Thread