Easy Tutorial
❮ C Exercise Example84 C Function Div ❯

C Language Example - Writing a String to a File

C Language Examples

Writing a string to a file.

Example

#include <stdio.h>
#include <stdlib.h>  /* exit() function */

int main()
{
   char sentence[1000];
   FILE *fptr;

   fptr = fopen("tutorialpro.txt", "w");
   if(fptr == NULL)
   {
      printf("Error!");
      exit(1);
   }

   printf("Enter a string:\n");
   fgets(sentence, (sizeof sentence / sizeof sentence[0]), stdin);

   fprintf(fptr,"%s", sentence);
   fclose(fptr);

   return 0;
}

Output:

Enter a string:
tutorialpro.org

Open the file tutorialpro.txt:

$ cat tutorialpro.txt 
tutorialpro.org

C Language Examples

❮ C Exercise Example84 C Function Div ❯