C language: Read and write data with character read stream and output stream. (text file)

Source: Internet
Author: User

  1. /*
  2. Several modes of operation of the file: R: Read-only W: write-only RW: readable and writable
  3. File classification: T: Text file (character file) B: Binary file (byte file)
  4. Attention:
  5. When opening a file with read-only mode, opening the file will fail if the source file does not exist!
  6. When you open a file in write-only mode, it does not fail, regardless of whether the source file exists. (Because a file is automatically created)
  7. When you open a file in a readable and writable manner, it succeeds.
  8. */
  9. #include <stdio.h>
  10. int main ()
  11. {
  12. //define file pointers
  13. FILE *fpin = NULL;
  14. FILE *fpout = NULL;
  15. //Open write file
  16. Fpin = fopen ("1.txt", "wt");
  17. if (fpin==null)
  18. {
  19. printf ("File open failed!\n");
  20. return-1;
  21. }
  22. //File write
  23. Char cs;
  24. While ((cs = GetChar ()) = = ' Q ')
  25. {
  26. FPUTC (cs,fpin);
  27. }
  28. //file close
  29. fclose (fpin);
  30. //Open read file
  31. fpout = fopen ("1.txt", "RT");
  32. if (fpout==null)
  33. {
  34. printf ("File open failed!\n");
  35. return-1;
  36. }
  37. //file read
  38. While (!feof (fpout))
  39. {
  40. //character read file
  41. char cc = FGETC (fpout);
  42. //Compare with EOF to determine whether to read the end of the file
  43. if (cc==eof)
  44. {
  45. Break ;
  46. }
  47. //output character
  48. Putchar (cc);
  49. }
  50. //file close
  51. fclose (fpout);
  52. return 0;
  53. }

C language: Read and write data with character read stream and output stream. (text file)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.