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}