Here is a program in C that illustrates the use of fprintf() to write a text file:

Program in C illustrating the use of fprintf() to write a text file:

#include <stdio.h>

int main() {
   FILE *fptr;
   fptr = fopen("output.txt", "w");
   if(fptr == NULL) {
      printf("Error!");
      return 1;
   }
   fprintf(fptr, "This is a text file created using fprintf!");
   fclose(fptr);
   return 0;
}

Explanation for each step:

  1. Include the necessary header file:
  2. #include <stdio.h>: This line includes the standard input/output header file, which contains the definition for the fprintf() function.

  3. Define the main function:

  4. int main() { ... }: This is the entry point of the program, where the execution begins.

  5. Declare a file pointer:

  6. FILE *fptr;: This line declares a file pointer fptr which will be used to handle the file operations.

  7. Open the file in write mode:

  8. fptr = fopen("output.txt", "w");: This line opens a file named "output.txt" in write mode. If the file doesn't exist, it will be created. If it does exist, its contents will be truncated.

  9. Check for file opening errors:

  10. if(fptr == NULL) { ... }: This condition checks if the file opening was successful. If the file pointer is NULL, an error message is printed, and the program returns with an error code.

  11. Write to the file using fprintf():

  12. fprintf(fptr, "This is a text file created using fprintf!");: This line uses the fprintf() function to write the specified text to the file pointed to by fptr.

  13. Close the file:

  14. fclose(fptr);: This line closes the file associated with the file pointer fptr after the writing operation is complete.

  15. Return from main function:

  16. return 0;: This line indicates a successful execution of the program, and the main function returns 0 to the operating system.