1, C Language file class, in the Stdio.h header file, the files class is a struct, defined as follows: A typedef defines the file type alias: "File", so that you need to read and write files in the future when the file is defined directly on the line.
Although I can not understand the parameters of the specific expression of what, but with this we use the computer experience is not difficult to know, the file property is nothing more than file name, modification time, permissions and other information
For example, we look at the properties of a Linux file:
This attribute is explained as follows:
(1)-rwxr-xr-x indicates that the user has permission to read the file.
(2) 1 indicates the number of connections to the file, that is, several files point to the file, thus enhancing security.
(3) Two root, which represents the group name of the owner and owner of the file, respectively.
(4) 6209 indicates the size of the file.
(5) Mar 30 13:59 indicates the last modification time for this file.
(6) Addoverflowdemo indicates the file name of this file.
Linux systems are mostly written in C, so the file structure of the Linux system should be similar to the files class, which basically represents this information.
Some of the information is automatically generated, such as the file's modification time, owner, file size, but some are required to create our own such as file name, file content, file read and write permissions.
1 Creating a fileThe following three points from the start to create a file: file name, file content, file read and write permissions. Method One:
Created by defining an instance, which is also the most basic way to create an instance in an object-oriented manner.
Defines a variable of type file and then initializes it.
FILE Filedemo;
Filedemo._ptr = ...
filedemo._cnt = ...
The code is as follows:
Compilation result: After a similar assignment, it is found that the compilation is not true. Tip, the file structure does not hold the specified variable that needs to be assigned.
This "struct." The method of assignment is not feasible, so it is better to assign a value by pointer.
Then initialize the file using one of the following methods
Method Two:
(1) Define a pointer to the file structure body
FIEL * FILE_DEMO;
(2) The value of the member variable initialized by the pointer. After the definition, you need to open up space first.
Method 1:file_demo = (file) malloc (sizeof (M))
How much is m set at this time? I don't know, because the number of characters the file needs to store is not yet clear, and it also requires an operation such as appending characters, so the following method of allocating space is used.
Method 2:file_demo = fopen ("Test.txt", "w"); This method has a variable space and also assigns the initial value.
Below, analyze the function of fopen:
fopen function prototype FILE *fopen (const char *filename, const char *mode);
where the parameter filename, as the name implies, is the file name, the const modifier is a constant and requires the full pathname.
The parameter mode is Chinese translation as a mode, but I prefer to translate it by the function it represents, translated here as "permission", the value that mode can obtain is:
Note that this parameter is also a constant string. The operation of the fopen function is like this, for "w" and "A" permissions, if there is a file named "filename", then directly manipulate the file, if not, create a new file. The other operation filename must exist.
The following creates a file with Write permissions:
File_demo = fopen ("/program/test.txt", "w");
A file named "Test.txt" is created, and the file is opened. Open successful return file pointer, open failed return null.
2 closing Files
The file needs to be closed after it is exhausted,
The function is fclose (FILE_DEMO);
Note that you must close the file after you have finished using it.
Example: Create a new file, write a string with the following code:
This program runs the platform Linux, the compiler is GCC
The running result of the program is to create the Test.txt file under/program. And the content is "Hello world!" and the same as expected.
3 reading and writing of files
3.1 Character level: FPUTC (), fgetc ()
function prototypes: int FPUTC (int c, FILE *FP);
Function: Writes the character C to the file pointed to by the FP.
Parameter: The range of C is in the range of the unsigned char type (0-255).
Return value: Run successfully returned this character, run failed, return EOF (-1).
Function prototype: int fgetc (FILE *fp);
Function: Reads a character from the file pointed to by the FP store in the return value.
Parameters: FP value, character manipulation source file.
Return value: The operation successfully returned the character, the operation failed (read to the end of the file file) returned "EOF"
3.2 FscanF (), FprinTF ()
function prototypes: int fprintf (FILE *stream, const char *format, ...);
Function: Outputs the contents of format formatted to the file that the stream points to.
Examples: fprintf (stream, "%s%c", S, c);
function prototypes: int fscanf (FILE *stream, const char *format, ...);
Example:
3.3 Line level: Fputs (), fgets ();
Function prototypes: Char *fgets (char *str, int num, FILE *FP)
Function: Reads the characters from the file referred to in the parameter FP to the memory space referred to by the parameter str until a newline character is present, the end of the file is read, or the num-1 characters are read, and then NULL is terminated as a string. So the maximum length of a string represents the maximum number of characters plus a null character. The difference between the fgets function and the Get function is that the GET function discards the newline character after it is encountered, and the Fgets function reaches the maximum character Max. Now that you have finished reading an entire line, it will add a newline character before the null characters in the string to identify the end of the line.
Parameter description: str: Save the string read from the file; FP: file pointer to the file to be read; Num: Indicates that a string that is read from a file does not exceed num-1 characters. After the last character that is read, add the string end flag ' \ s '
return value: The str pointer is returned if successful, and NULL is returned if unsuccessful
Char *fputs (char *str, FILE *FP)
Function: Writes the string referred to by the parameter str to the file referred to in the parameter FP. The puts function appends a newline character to the output, and the Fputs function does not add a newline character when it is printed. So the fgets function should be used with the fputs function instead of the puts function. Otherwise, the input has a newline character and the output becomes two.
Return value: Success returns the written string, and the failure returns EOF
Example:
#include <stdio.h>
Main ()
{
Char s[80];
Fputs (Fgets (S,80,stdin), stdout);
}
Execute this is a test/* input */
This is a test/* output */
3.4 Block-level fread (), fwrite (), implements the operation of the data block, can be read and written in binary files
size_t fread (void *ptr, size_t size_of_elements, size_t number_of_elements, FILE *a_file);
size_t fwrite (const void *ptr, size_t size_of_elements, size_t number_of_elements, FILE *a_file);
Function:
Fread: Reads size_of_elements X number_of_elements data from a file pointed to by A_file and stores it in the memory that PTR points to.
Fwrite: Reads size_of_elements X number_of_elements data from the memory pointed to by PTR and stores it in the file pointed to by A_file.
Parameter description:
void * PTR represents the array name you need to write to the A_file file , or pointers to other structures , etc.
A size_of_elements represents the size of each element in an array or other structure.
Number_of_elements indicates how many elements size_of_elements X number_of_elements are the total size.
The front is enough to read and write files, so far, we have just used them for sequential access, that is, processing the contents of the file sequentially. Below, let's say random storage, that is, accessing the file contents in any order you want.
3.5 Random Storage: fseek (), Ftell ();
int fseek (FILE *fp,long offset,int origin);
Function: Moves the FP file read-write location pointer to the specified location.
Parameters: FP points to the file pointer being searched, the file should have been opened with fopen (). Offset, which is referred to as offsets, indicates the distance to move from the starting point, offset must be a long value, positive (migrated), negative (trailing), 0 (remains fixed). Origin represents a pattern used to identify the starting point. The following is the pattern constant specified by the stdio.h header file:
Return value: If everything is OK, the return value is 0; If an error occurs, such as an attempt to move beyond the file range, the return value is-1
Example: Feek (FP, X, Seek_set);//Find the 10th byte of the file
Long Ftell (FILE *FP)
Function: Gets the current read and write location of the streaming file. function to determine the location of a file by returning the number of bytes from the beginning of the file
Return value: The number of bytes of the file's current read and write location from the beginning of the file
Example:
Feek (FP, 0, seek_end);//Set the current position to offset 0 bytes from the end of the file, that is, set the position at the end of the file. The following statement:
Last=ftell (FP);//assigns the number of bytes from the beginning of the file to the end of the file to the last. Next is a loop:
for (count=1; count<=last; count++)
{
Fseek (FP,-count, seek_end);//Fallback
CH=GETC (FP);
}
The first loop navigates the program to the first character before the end of the file, which is the last character of the file. Then print this character. The next loop navigates the program to the previous character and prints it. This operation will continue to reach the first character and print it.
3.6 redirects: Rewind ();
int Rewind (FILE *stream);
Function: Points The file pointer back to the beginning of a stream.
For example: In general we will get the number of characters in the file by the following method:
File *fs=fopen ("C:\1.txt", "R");//Creating a stream
Long length=0;//declares file length
Fseek (fs,0,seek_end);//Place the internal pointer of the file on the last side of the file
Length=ftell (fs);//Read the position of the file pointer, get the number of file characters
Rewind (fs);//Reset the file pointer to the front of the file
A detailed description of C language files