File-related operations in C Language
I. first introduce the data file type:
1. Binary File (image file): It is accessed in binary format in memory.
2. Text Files (ascii files): files accessed in the form of ascii code.
In general, on Mac, you can drop a file into the notepad. If it is garbled, It is a binary file.
2. file type pointers:
Simply put, the file type pointer is the address used to store the file information.
File Type pointer variable: defines a pointer type variable to point to the address that stores file information. Use FILE. For example, FILE * fp
3. File Operation steps (all functions used in C Language start with f .) :
1. open the file fopen () function. Fp = (file name, "Operation Method") for example: fp = fopen (/user/wangdi/desktop/haha.txt, w) for example, you can view the file path by throwing the file into the terminal on Mac.
2. Read and Write the file (read the bytes in the file .)
To write information to a file:
Fputc () function. Write one byte at a time. Format: fputc (Data ascii code, file stream ). For example, fputc (97, fp) is used to write the ascii code corresponding to 97 to the file pointed to by fpz. That is, write a in. For example, write the string: 12345 In the str string in a loop:
Read information from a file:
Fgetc (File pointer ). Read one byte from the file. Note: If the file contains Chinese characters, the function extracts one byte at a time, so garbled characters are extracted.
If it is extracted as-1 in the form of % d, it indicates the end of the file. In actual development, it is often used as follows: while (ch = fgetc (fp ))! =-1) {printf (% c, ch)}. For example:
3. Examples of File Operations used in functions:
A: Short for append. Append file: open the file, move the cursor to the end of the file, and create the file if the file does not exist.
R.: Short for read. Reading a file: Open the file. If the file does not exist, null is returned.
W: write is short for opening a file. If a file exists, it is truncated (the file is cleared). If no file exists, the file is created.
A +, r +, w +, and so on: Add readable and writable functions to the original functions. I will not introduce them one by one here.
2. File Processing: Use a function to write data to the stream or read data from the stream.
3. close the file: fclose () function. Note: In the program, each time you call a function, you need to open and close the file, that is, you need to use the fopen () and pclose () functions.