[Let us C Solution ] C Program To Writing And Reading To A Text File




Example 1: Write to a text file using fprintf()






  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. int main()
  4. {
  5. int num;
  6. FILE *fptr;
  7. fptr = fopen("C:\\program.txt","w");
  8. if(fptr == NULL)
  9. {
  10. printf("Error!");
  11. exit(1);
  12. }
  13. printf("Enter num: ");
  14. scanf("%d",&num);
  15. fprintf(fptr,"%d",num);
  16. fclose(fptr);
  17. return 0;
  18. }

Example 2:Read to a text file using  scanf()

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. int main()
  4. {
  5. int num;
  6. FILE *fptr;
  7. if ((fptr = fopen("C:\\program.txt","r")) == NULL){
  8. printf("Error! opening file");
  9. // Program exits if the file pointer returns NULL.
  10. exit(1);
  11. }
  12. fscanf(fptr,"%d", &num);
  13. printf("Value of n=%d", num);
  14. fclose(fptr);
  15. return 0;
  16. }



Comments

Popular posts from this blog

HTML Signup Login Form With Source Code