Explanation of file operations and pre-processing commands in C language and pre-processing

Source: Internet
Author: User

Explanation of file operations and pre-processing commands in C language and pre-processing
1. File Operations

The file is divided into two parts: control information and content information

Text Files and images are essentially binary files, but the control information is different.

File Read process: disk (get binary files) File Buffer application memory space

Various types of files seen in widows, such as jpg, png, and avi, are only encoded and decoded Based on the file control information when reading the File Buffer from the disk.

What is the difference between reading and writing a C binary file and a text file:

Binary: write the text '\ N'-> \ r \ n

Binary: Read text \ r \ n-> \ n

1. read and Write files
//// // Read the int main () {char * path = "G: \ 0_preClass \ NDK \ class \ Ls_C5 \ files \ friends.txt "; FILE * fp = fopen (path," r "); char buff [500]; while (fgets (buff, 50, fp) {printf ("% s", buff);} fclose (fp); system ("pause"); return 0 ;} /// // write a file ///// /// // int main () {char * path = "G: \ 0_preClass \ NDK \ class \ Ls_C5 \ files \ friends_write2.txt"; // if the FILE does not exist, a FILE is created. * Fp = fopen (path, "w"); if (fp = NULL) {printf ("failed .... "); Return 0;} char * text =" Hello, WTF? "; Fputs (text, fp); fclose (fp); system (" pause "); return 0 ;}
2. Read and Write binary files
/// // Read/write binary file int main () {char * read_path = "G: \ 0_preClass \ NDK \ class \ Ls_C5 \ files \ LogViewPro.exe"; char * write_path = "G: \ 0_preClass \ NDK \ class \ Ls_C5 \ files \ LogViewPro_write.exe "; // read: B of rb is in binary format, without B, FILE * read_fp = fopen (read_path, "rb"); // write FILE * write_fp = fopen (write_path, "wb "); char buff [50]; int len = 0; // read 50 sizeof (char) characters each time from read_fp While (len = fread (buff, sizeof (char), 50, read_fp ))! = 0) {fwrite (buff, sizeof (char), len, write_fp);} fclose (read_fp); fclose (write_fp); system ("pause"); return 0 ;}
3. size of the file
Int main () {char * read_path = "G: \ 0_preClass \ NDK \ class \ Ls_C5 \ files \ liuyan.png"; FILE * fp = fopen (read_path, "r"); if (fp = NULL) {return 0 ;}// set the stream file location to the given offset, the offset parameter indicates the number of bytes to be searched from the given whence position. Fseek (fp, 0, SEEK_END); // returns the current file location of the given stream. Long filesize = ftell (fp); printf ("% ld \ n", filesize); system ("pause"); return 0 ;}
4. encryption and decryption of text files
// ^ XOR operation 7 (0111) // 1001 ^ 0111 = 1110 // 1110 ^ 0111 = 1001 void encode (char normal_path [], char encode_path []) {FILE * normal_fp = fopen (normal_path, "r"); FILE * encode_fp = fopen (encode_path, "w"); int ch; while (ch = fgetc (normal_fp ))! = EOF) {fputc (ch ^ 7, encode_fp);} fclose (normal_fp); fclose (encode_fp);} void decode (char encode_path [], char decode_path []) {FILE * normal_fp = fopen (encode_path, "r"); FILE * encode_fp = fopen (decode_path, "w"); int ch; while (ch = fgetc (normal_fp ))! = EOF) {fputc (ch ^ 7, encode_fp);} fclose (normal_fp); fclose (encode_fp);} int main () {char * nomal_path = "G: \ 0_preClass \ NDK \ class \ Ls_C5 \ files \ friends.txt "; char * encode_path =" G: \ 0_preClass \ NDK \ class \ Ls_C5 \ files \ friends_encode.txt "; char * decode_path =" G: \ 0_preClass \ NDK \ class \ Ls_C5 \ files \ friends_decode.txt "; // encode (nomal_path, encode_path); decode (encode_path, decode_path ); system ("pause"); return 0 ;}
2. Preprocessing commands

Preprocessing command:

First, you must understand the execution process of the C language. First, the C language will (. c. cpp) is generated by compilation. obj. After the object is generated, the obj files of each target file are bundled by the linker to form a library (exe file pdb dll so)

There are two other processes when generating. obj. The first one is the pre-processor stage (read all the executable files on the source file # define # include)

Note: # include is run in the preprocessing phase, that is, text replacement.

1. Small Example

A.txt File

printf("hello WTF? \n");
# Include
 
  
# Include
  
   
// # Define identifier string // string replacement // typedef alias # define MAX (x, y) (x)> (y ))? X: y # define Mint main () {# include "A.txt" for (int I = 0; I <5; I ++) {printf ("% d \ n ", i);} int max = MAX (3, 5); printf ("% d \ n", max ); # ifdef N # ifdef M printf ("% d \ n", 110); # else printf ("% d \ n", 120 ); # endif # ifndef X printf ("% d \ n", 130); # endif system ("pause"); return 0 ;}
  
 
2. Detailed Description
The process of executing the pre-processing command in C language: 1. Each source file of the program is converted into the object code through the compilation process. 2. Each target file is bundled by a connector, A single and complete executable file is formed, and the compilation process is composed of the following processes: 1. in this phase, the pre-processor performs some text operations on the source code. For example, replace the symbols defined by the # define command with actual values and read the content of the files contained by the # include command. 2. The source code is parsed to determine the meaning of its statement. This stage will generate a vast majority of errors and warning information, and then generate the target code. Execution phase: 1. The program must be loaded into the memory. 2. Program Execution 3. The last stage of program execution is program termination. The role of the Define command does not have a macro definition # the definition of the string of the define identifier is a constant meaning: it is the role of macro replacement, so that the identifier replaces the string, this is just a simple text replacement, the Preprocessing Program does not perform any checks on it. If any error occurs, it can only be found when the source program that has been expanded by a macro is compiled. Counterexample # define pint (int *) pint pa, pb; the intention is to define both pa and pb are int type pointers, but actually it is int * pa, pb ;. Pa is an int pointer, while pb is an int variable. In this example, typedef can be used to replace define, so that both pa and pb are int pointers. The macro definition is only a simple string replacement, completed in the preprocessing phase, while typedef is processed during compilation. It is not a simple replacement, but a new name for the type specifier, the name of the identifier has a type definition description. No macro parameters. Note :? Macro names are generally expressed in uppercase letters to facilitate differences with variables .? Do not add points at the end of the macro definition; otherwise, replace them with semicolons .? Macro definitions can be nested .? Use the # undef command to terminate the macro-defined scope .? Using macros improves program versatility and accessibility, reduces inconsistencies, reduces input errors, and facilitates modification. For example, macro definitions are commonly used for array size .? Preprocessing is performed before compilation, and one of the compilation tasks is syntax check. Preprocessing does not perform syntax check .? The macro definition is written outside the curly braces of the function, and the scope is the subsequent program, usually at the beginning of the file .? The string "" Never contains a macro. Otherwise, the macro name is processed as a string .? Macro definition does not allocate memory, variable definition allocates memory. Macro definition with parameters # define macro name (parameter) string example: # define INC (x) x + 1y = INC (5); counterexample: # define SQ (r) r * rY = SQ (a + B); Result = a + B * a + B; Use Case: The maximum and minimum values of the most common alternative solution area: # define MAX (x, y) (x)> (y ))? (X): (y) The file contains the command to insert the specified header file into the command line to replace the command line, so that the specified file and the current source file are connected into a source file. File Inclusion is useful in programming. A large program can be divided into multiple modules and programmed separately by multiple programmers. Some common symbolic constants or macro definitions can be used to form a single file. You can use the include command to include the file at the beginning of other files. In this way, you can avoid writing the public amount at the beginning of each file, saving time and reducing errors. The difference between # include <> or # include "" <> and "" is: use "" to search in the directory containing files (including the directory is the include directory set by the user when setting the environment "solution Manager-> properties-> Configuration properties-> VC + + directory "), instead of searching in the current source file directory, double quotation marks are used to search in the current source file directory first. First method of Conditional compilation # ifdef identifier (or # if defined) Section 1 # else section 2 # endif or # ifdef identifier (or # if defined identifier) program section # endif method 2 # ifndef # else # endif method 3 # if # else # role of endif in practice: 1. shielding cross-platform differences during large-scale development, especially in cross-platform and system software, you can set the compiling environment through Conditional compilation during compilation. # Ifdef WINDOWS # define MYTYPE long # else # define MYTYPE float # endif2. contains program function modules # ifdef FLV Include "fastleavec" # endif is not allowed to provide this function to other users, add the first FLV to the horizontal line before compilation. switch debugging information # ifdef DEBUG Prinft ("device_open (% d) \ n", file); # endif DEBUG is a switch. In a public header file of the entire project, we can turn this switch on when we are in the debug stage. When our program is in the release version, we will turn this switch off. 4. to avoid hardware restrictions, sometimes the hardware in some specific application environments is different, but due to the lack of such a device locally, you can bypass the hardware and directly write the expected results: # ifndef test I = dial (); # else I = 0; # endif5. prevent repeated header files from being contained by header files or C files. Because header files can be nested, C files may contain the same file multiple times; or different C files may all contain the same header file, which may cause Repeated inclusion during compilation. # Ifndef HEAD_A # define HEAD_A # include <> # endif

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.