C language-file read/write and output, C language read/write

Source: Internet
Author: User
Tags rewind

C language-file read/write and output, C language read/write

In C, file operations are important. The following code creates, reads, and writes, and displays files.

In addition, files are displayed in binary format to reflect the real storage mode of files in the computer.

The specific code implementation process is as follows:

1 # include <stdio. h> 2 # include <stdlib. h> 3 # include <windows. h> 4 int main () 5 {6 FILE * fp; // defines a pointer to a FILE type variable 7 int num; 8 char name [10]; // define a character pointer 9 char pstr; // Temporary Variable 10 char word [100]; // as the temporary variable for writing text 11 char temp [8]; 12 printf ("new file name:"); 13 scanf ("% s", name); 14 fp = fopen (name, "w + "); // create a text document 15 if (! Fp) 16 {17 printf ("the file is not created successfully! "); // If no file exists, return the value 18 exit (1) to the function; // exit program 19} 20 printf (" Enter the text :"); // prompt to enter the text 21 scanf ("% s", word); // space is also used as the string Terminator 22 // gets (word ); // only press enter as the string Terminator 23 fputs (word, fp); // write the string 24 printf ("file content (displayed in text format) to the file :"); 25 // rewind (fp); // The file Pointer Points to the beginning 26 fseek (fp, 0, SEEK_SET); 27 while (pstr = fgetc (fp ))! = EOF) 28 {29 putchar (pstr); // display file content 30} 31 rewind (fp); 32 printf ("\ n in binary format :"); 33 while (pstr = fgetc (fp ))! = EOF) 34 {35 num = (int) pstr; // convert character to ASCII code 36 itoa (num, temp, 2); 37 printf ("% s ", temp); 38} 39 fclose (fp); // close the file 40 return 0; 41}

 

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.