user2692751
user2692751

Reputation: 101

Enter text and save to file

The following function creates a new text file and allows the user to input text to be saved to the file. The main issues that I'm having troubles fixing is 1)allowing spaces between words 2)hitting enter saves the text, instead of going to a new line.

void new_file(void) 
{
    char c[10000];              
    char file[10000];
    int words;
    printf("Enter the name of the file\n");
   scanf("%123s",file);
    strcat(file,".txt"); 
    FILE * pf; 
   pf = fopen(file, "w" );

   if (!pf)
   fprintf( stderr, "I couldn't open the file.\n" );

   else
   {
        printf("Enter text to be saved\n");
        scanf("%s", c);     
        fprintf(pf, "%s", c); 
    }

    fclose(pf);  // close file  
    printf("\n\nReturning to main menu...\n\n"); 
}

Upvotes: 1

Views: 132

Answers (1)

alk
alk

Reputation: 70941

Use fgets() instead of scanf() to get the input text from the user.

To do so replace this line

scanf("%s", c); 

with the following code:

if (NULL != fgets(c, sizeof(c), stdin))
{
  fprintf(pf, "%s", c);
}
else
{
  if (0 != ferror(stdin))
  {
    fprintf(stderr, "An error occured while reading from stdin\n");
  }
  else
  {
    fprintf(stderr, "EOF was reached while trying to read from stdin\n");
  }
}

To allow the user to read in more then one line put a loop around the code above. Doing so you need to define a condition which tells the program to stop looping:

The following example stops reading in lines when entering a single dot "." and pressing return:

do
{
  if (NULL != fgets(c, sizeof(c), stdin))
  {
    if (0 == strcmp(c, ".\n")) /* Might be necessary to use ".\r\n" if on windows. */
    {
      break;
    }

    fprintf(pf, "%s", c);
  }
  else
  {
    if (0 != ferror(stdin))
    {
      fprintf(stderr, "An error occured while reading from stdin\n");
    }
    else
    {
      fprintf(stderr, "EOF was reached while trying to read from stdin\n");
    }

    break;
  }
} while (1);

Upvotes: 1

Related Questions