Chapter II problem solving and programming
Basic knowledge
Basic framework
// Basic composition = header file + declaration + main function #include<stdio.h> int a = 8; void main() { // Code block return 0; }
Common header file
#include<stdio.h> #include<string.h> #include <stdlib.h>
----Remember to add these header files every time
Escape sequence
Escape sequence | meaning |
---|---|
\n | Line feed |
\r | Output carriage return [no line feed] |
\a | Ring the bell |
\b | Backspace |
scanf
scanf("%d%d",&a,&b);
----Assign the obtained values to a and b respectively in order
----Note that the address fetching character & should be used to assign values
----Notice that both printf and scanf use double quotes
----&Is the address character, &b is actually the memory address of B
----If you enter, you don't need to consider whether there is space between placeholders, such as scanf_ s("%d%d", &a, &b); And scanf_ s("%d %d", &a, &b); The input method is actually the same. Enter a value and press enter, then enter a value and then press enter; That is, the interpreter will automatically distinguish between two inputs
printf
printf("a=%d,b=%d",a,b); printf("i=%o\n",x.i); printf("ch0=%o,ch1=%o\n ch0= %c,ch1 =%c\n"; x.ch[0],x.ch[1],x.ch[0],x.ch[1]);
----When outputting, you can add necessary characters at both ends to adjust the output content without affecting the formatting
----The output parameters can directly call variables to realize the formatted replacement of the output content
----Notice that both printf and scanf use double quotes
----You need a newline character to ensure that each output is not next to each other
----Note that when printf is output, the corresponding recognition method will be generated for the input data according to the formatted characters
placeholder
- %d: Used to output signed decimal integers (including int / char types)
- %u: Used to output unsigned decimal integers (including int / char types)
- %o: Used to output unsigned octal integers
- %x: Used to output unsigned hexadecimal integers
- %c: Used to output a single character
- %s: Used to output a string
- %f: Decimal floating point number used to output decimal form (both decimal form and exponential form can be recognized when entering)
- %e: Decimal floating point number used to output exponential form (both decimal form and exponential form can be recognized when entering)
- %g: It is used to output decimal floating-point numbers that are shorter in both exponential form and decimal form (both decimal form and exponential form can be recognized when inputting)
- %. 2lf: used to output the form with two decimal places reserved
----It is widely used in input and output statements
----Bold and black are common placeholders
----%m.nf m is the number of characters of the output data, and n is the accuracy of the output data
data type
A
----An abstract operation that summarizes the characteristics of data + corresponding definitions
----The size of the data type is queried by sizeof operation
integer
----Limited size
----Usually a 4-byte memory unit
----It can perform arithmetic operation, assignment operation and relationship operation
constant
----A way of storing data
#define PI 3.1415926const double eps = 0.001; // Error accuracy
variable
----A way of storing data
----Variables are used to temporarily store raw data
----The specific object of data type is an area in memory, which can store and delete data
----When the compiler encounters a variable declaration statement, it allocates the specified storage space for the variable according to the data type
----Basic structure: variable type variable name (identifier)
----double percent2=1.00;–> The equals sign here is not an assignment operation, but an initialization. This statement is still a variable declaration statement
----Statement example
double high; double high,faHeight,moHeight; double high,faHeight,moHeight,percent1=1.00,percent2=1.00;
symbolic constants
#define pi 3.1415926
----This operation is called macro definition
----You can put symbols as variables in your code
----It is a command executed in the preprocessing phase, which will replace the pi in the code with 3.1415926 one by one, so it does not occupy memory space
Data type conversion
Implicit conversion ---- during operation, the computer will automatically round off the low precise value or fill in zero according to the operation to force the operation of data – > the computer will automatically convert the type of input data into the specified format for processing in order to enter the operation function for processing
Explicit conversion -- programmers convert manually through code – >
– > eg. (type name) expression – > average = (float) (1 + 2) – > the value of average is 3.000000
Operation priority
operator | meaning | Associativity |
---|---|---|
() | brackets | |
+ - | Monocular operation, positive and negative | Right to left |
* / % | Binocular operation, multiplication and division, remainder | From left to right |
+ - | Binocular operation, addition and subtraction | From left to right |
= | Binocular operation, assignment | Right to left |
----The higher the priority, the higher the priority
Chapter III problem solving and programming
Basic knowledge
Logical operation
----Use the formula of = to obtain the logical truth and false by whether the equal sign is true or not
----Logical true is 1 and logical false is 0
----Logical true and false 0 and 1 are actually int types
Branching structure
if
if (a==b) { printf("a and b equal\n"); printf("a and b equal\n"); }
or
if (a==b) { printf("a and b equal\n"); printf("a and b equal\n"); } else { printf("a and b Unequal\n"); printf("a and b Unequal\n"); }
or
if(i >= 'a' && i != 'q' && i<='z') { xiaoxie++; } else if(i >= 'A' && i != 'Q' && i<='Z') { daxie++; } else { qita++; }
or
//Nested if if(grade>=60 ) if(grade<70) if(grade%2==0) printf ("Passed! \n") ;
----Note the use of if and else
switch-case
char op; double a,b,result; scanf("%lf %c %lf",&a,&op,&b); switch (op) { case '+': printf("%.2lf",(double)a+b); break; case '-': printf("%.2lf",(double)a-b); break; case '*': printf("%.2lf",(double)a*b); break; case '/': if(b==0) { printf("Divisor cannot be 0"); break; } printf("%.2lf",(double)a/(double)b); break; default: printf("Incorrect operator"); }
----Judge which part of the statement is executed by the value of the variable inside the switch bracket
----It can be noted that internally, variables and conditions are compared and judged directly through the case. When the judgment execution statement ends, you need to use break to jump out of the code block of the current case; Just type the code directly after the quotation marks
----default is used to perform additional operations without case matching. You don't need to break. You can just type the code after the quotation marks
----switch is actually a multi branch if else statement to judge whether the value of the input variable is equal to the branch content of case. It can be regarded as connecting through = = in the middle
Ternary operation
----Approximate format – > condition? Operation_ 0: Operation_ one
----? And: called conditional operators
----When the condition is true, execute the operation_ 0, otherwise perform the operation_ one
Character variable ASCI I code
----Character types are actually represented using binary encoding
----In this way, 'a' is the binary code of the letter A, and the single quotation mark is a tool for converting characters into binary code -- it is represented by binary code character by character
//Assign values to characters int main() { char c='a'; printf("%c",c); return 0; } //----This return value is a, which must be expressed in single quotation marks and ASCI I code. Using double quotation marks will report an error
getchar and putchar
a = getchar(); putchar(a);
----The output of a is equivalent to scanf and printf, which are simplified input-output statements
Logical operation
----Arithmetic operation > relational operation > logical and operation > logical or operation
----Short circuit of logic operation: the expression of logic and operation, which operates from left to right, does not need to be calculated in case of 0; The expression of logical or cannot continue to calculate to the right when encountering 1 [the attribute of and or gate itself]
----Is used to represent the door
Chapter IV repetition and iteration
Basic knowledge
while
Self operation
#include "stdio.h" int a = 1; int main(){ printf("a = %d ", a++); return a; } /*--------------------Split line--------------------*/ #include "stdio.h" int a = 1; int main() { printf("a = %d ", ++a); return a; } /*--------------------Split line--------------------*/ #include "stdio.h" int a = 1; int main() { printf("a = %d ", a+=1); return a; }
----C language self addition and self subtraction operator (+ + i / i++) Leon calls it self operation, which is convenient for overview and memory
---- printf("a = %d ", a++); The meaning of a is to output a to a first, and then + 1. Because + + is after the variable, the output is 1
---- printf("a = %d ", ++a); The meaning of is to perform the + 1 operation first, and then perform the output operation of A. because + + is in front of the variable, the output is 2
----printf("a = %d ", a+=1); The meaning of a is to perform + 1 operation first, and then perform a output operation on a, and the output is 2
----The same is true for other similar operation symbols
for
for(j=1;j<=i;j++) { printf("%d",j); printf("%d",j); } /*--------------------Split line--------------------*/ for(;;num++) { scanf("%d",&a); if(a<=0) { break; } sum+=a; if(a<60) { failed++; } }
----The first parameter is the initialization of variables
----The second parameter is to judge whether iteration is required, which is the starting point of each small loop
----The third parameter is used for the end of the for loop to avoid infinite loop. The operation of the third parameter will be executed only when the program in parentheses ends
----You can see that the initial parentheses of the for loop statement can be left blank as long as the code is reasonable
do while
/*From 1 to 100*/ #include <stdio.h> int main0 int i= 1,sum=0; do { sum=sum+i; i++; } while(i<= 100]; printf("sum=%d\n" ,sum); return 0; }
----The difference from while is that while judges before execution, while do while executes before judgment
continue
void main() { int i=0; while(i<10) { if(i<1)continue; if(i==5)break; i++; } }
----It is used to jump out of this cycle of the cycle body and enter the next cycle; Corresponding to break
Chapter V
Basic knowledge
function
Data type function name (parameter) of the return value_0,parameter_1) { return ; }
Function declaration
long fact(long a);
----It is used to avoid that functions cannot be read normally due to the order relative relationship between functions
----The function name and parameters should be written
----Such a function form is called a function prototype. At this time, the name of the formal parameter is actually optional. The compiler is related to the type and quantity of the parameter
----When the program is executed, calling the function is actually to find the definition of the function and jump to the place of the function definition to execute the code
driver function
----Driving function
----Test function
----main function
Local and global variables
----Local variables are defined in the function and only take effect in the code block in which the function runs
----When the global variable has the same name as the local variable, the local variable works inside the function and the external variable is ignored
----Global variables occupy storage units throughout the process, reducing memory utilization
----The versatility of functions is reduced, which is easy to cause name collision – > great interaction
----Make it difficult for people to read
Chapter 6 array
Basic knowledge
A
// Define an integer array num, which has 5 elements num[0],num[1],num[2],num[3],num[4], and counts from 0 int num[5] //Array load value for(j=0;j<10,j++) scanf("%d",&a[j]); //Array output value for(j=0;j<10,j++) printf("%d",a[j]);
----When defining an array, the number in square brackets means the number of elements contained in the array, and the subscript value starts from 0
----When defining an array, the number in square brackets cannot be a variable, but only a constant
----The system does not check for out of bounds of array element subscripts
Array creation
int num[5] scanf("%d",&a[0]) //The initialization methods are all equivalent to the following methods int a[5] = {6,2,4} int a[5] = {6,2,4,0,0} int a[ ] = {6,2,4,0,0} a[0]=6,a[1]=2,a[2]=4,a[3]=0,a[4]=0
----Define an integer data num, which contains five elements: num[0],num[1],num[2],num[3],num[4]
----Focus on the use of arrays - reference variables, which is similar to the use of variables
----Focus on initialization mode
Two dimensional array
// Position by position assignment one by one int a[3][4] = {{1,2,3,4},{1,2,3,4},{1,2,3,4}} int a[3][4] = {1,2,3,4,1,2,3,4,1,2,3,4} // Assignment of some elements int a[3][4] = {{1},{1,5},{1,2,3}} ----The area where the first number is located corresponds to the first layer of parentheses---First dimension // The first dimension may be omitted and the second dimension may not be omitted int a[][4] = {1,2,3,4,5,6,7,8,9,0} int a[][4] = {{0,0,3},{},{0,10}}
Character array
A
//initialization char ch[5] = {'2','2','2','2','2'} char ch[5] = {'2','2','2'} --Store results-->{'2','2','2',\0,\0} char ch[5] = {'Hi'} --Store results-->{'H','i',\0,\0,\0} char ch[][4] = {{'0','0','3'},{},{'0','10'}}-->It is almost the same as an ordinary array
----The last bit of the character array is always \ 0, so 11 bits are required to store ten elements, and the system will automatically supplement them -- the number of positions needs to be estimated during creation, and the position should be reserved for the terminator
----scanf printf automatically matches the terminator mechanism of the string internally
Character processing
//Get and output string puts(str); /* print(%os",str); */ gets(str); /* scanf("%s",str); */ //Splice string {char a[20] ="Visual"; char b[]="C++"; strcat(a ,b); printf("%s\n", a);// Visual C++ //Copy b into a or c char b[]= "C++", c[] ="Visual"; strcpy(a, c); strcat(a, b); printf("%s\n", a); //Compare the size of ASCI codes one by one from left to right //If string 1 < string 2, return a negative integer; If string 1 > string 2, return a positive integer; Returns zero if string 1 = = string 2 char str1[] ="Hell0!", str2[] ="Hello!"; if(strcmp(strl, str2)>0) printf("Hell0!> Hello!"); else if(strcmp(strl, str2)==0) printf("Hell0!= = Hello!"); else printf("Hell0!< Hello!"); //Get character length char str1[] = "Hello!"', str2[] = "How are you?"; int len1,len2,len3; len1=strlen(str1) ; len2=strlen(str2); printf(len1=%d len2=%d",len 1,len2); //Case conversion //strlwr(str) function: converts uppercase letters to lowercase letters in a string //strupr(str) function: converts lowercase letters into uppercase letters in a string //Convert string to floating point number a = atof(strA);
Array as parameter
//One dimensional array void sort(int array[],int n); //Two dimensional array void sort(int array[][10],int n);
----The focus is on the difference in description attributes when filling in the array as a parameter
----You can see that you do not need to enter the length and size of the array to enhance applicability
Array application
Bubble sorting
#include <stdio. h> / / bubble sorting optimization #define N 6 void main ( ) { int a[N], i, j, t,flag=1;//When it is 1, it indicates that there is an exchange //Enter N integers -- get data printf ("input %d numbers: \n", N); for(i=0;i<N; i++)scanf ("%d", &a[i); //sort for(i=1;i< N; i++) //N-1 bubble sort { if(flag== =0) break; //Indicates that there was no exchange in the previous - trip---- else {flag=0; //The initial is no exchange for(j=0;j<N_i; j++)//Bubble sort { if(a[j] > a[j+1]) //Exchange a[j] and a[j+1] {t= a[j]; a[j] = a[j+1]; a[j+1]= t; flag=1;} } } printf ("the sorted numbers:\n"); for(i=0;i<N; i++)printf ("%d ", a[i]);, }
lookup
Sequential search
----In fact, Zhuge = = search one by one
#include <stdio.h> #define N 6 void main() { int i,X; int array[N]={9,7,2,8,1,6}; printf("please input search x="); scanf("%d" ,&x); for(i=0;i<N;i++) //Sequential search { if(array[i]==x) { print("i=%d,x=%d\n",i,x);//Search succeeded break; } } if (i= =N) printf("not found\n");//Search failed }
Half search
----The premise of use is that it is orderly
void main() { int x,low,high,mid; int array[N]={1,2,6,7,8,9}; printf(" please input search x="); scanf("%d",&x); low=0; high=N-1; mid=(low+high)/2; while(low< =high && array[mid]!=x) //Continue to find in half { if(x<array[mid]) high=mid-1; else low=mid+1; mid=(low+high)/2; if (low>high) printf("not found\n";//Search failed else print("i=%d,x=%d\n",mid,x);//Search succeeded }
insert
...
delete
...
Chapter VII pointer programming
Basic knowledge
A
----When a variable is defined in the program, when the program is compiled, the system will allocate memory units for the variable, and create a space field for the variable according to the size of the defined data type. This space is represented by a location number, which is the address
----The required variable unit can be found through the address. It can be said that the address points to the variable unit. Such an address is called a pointer
----The address consists of the memory number of the corresponding data and the data type of the corresponding data
----Direct access using variable names is called direct access, and access using pointers is called direct access
----Only one address can be stored in the pointer variable, which is an integer value
----Indirect accessor: ** The operation can search the data stored in the position of the corresponding value
initialization
int num=3; int * num_in ;//Pointer to integer num_ The name of the in pointer is num_0 num_in = & num;//Assign the address of the variable to the pointer, and the variable corresponding to the pointer is num //*num_ The value of in is 3
be careful
int num=3; int * num_in ; num_in = & num; //*num_ The value of in is 3 num = 4; printf("%d",*num_in);//The output is 4 //It is understood that the value at the corresponding position can be modified directly through the pointer or through the variable. In essence, the pointer and variable are a way to query and modify a storage area of the computer, just a tool and an index method int a[4]; int *p = a; //It is understood that the first address of data can be recorded through the pointer, and then when reading information through the pointer, the data type information can help the computer read the number of bits specified behind the pointer and carry out relevant operations
&And*
----One is the address character and the other is the pointer operator. When two appear at the same time, they offset each other and have no effect -- the offset between reciprocal operations
Pointers and functions
Pointer as parameter
----The call of a function can only return one value, so you can return a value with the help of a pointer, which is equivalent to returning multiple values
#include <stdio.h> void swap(int a, int b){ int temp; //Temporary variable temp = a; a = b; b = temp; } int main(){ int a = 66, b = 99; swap(a, b); printf("a = %d, b = %d\n", a, b); return 0; } //-->The output is 66 99 //-----------------Use pointer--------------------- #include <stdio.h> void swap(int *p1, int *p2){ int temp; //Temporary variable temp = *p1; *p1 = *p2; *p2 = temp; } int main(){ int a = 66, b = 99; swap(&a, &b); printf("a = %d, b = %d\n", a, b); return 0; } //-->Output is 99 66
----Some understand that the function itself is to transfer the input parameters into the special area of the function for related processing, which will not affect the original external variables. As can be seen from the first paragraph of code
----However, if you first tell the function that the pointer is passed in, you can change the value of the external function by indexing the corresponding address through the pointer
Pointer to function
----The entry address assigned to a function at compile time is called a pointer to the function and is represented by the function name
----I need to see it after here
//Pointer to function int man(int,int),(*p)(); c = (*p)(a,b) //--> c = max(a,b)
A function whose return value is a pointer
int *f(int x,int y)//Simply add a * symbol
Pointer and string
char *string = "I love china"; //String is defined as a pointer variable of character type. During the above operation, the first character of the whole string is passed to the pointer variable. String is used to point to the address //The method of use is shown in the figure string = "i am a student"; printf("%d",string);//-->i am a student //The system will automatically output the string bit by bit //-----------------Split line--------------------- #include <stdio.h> int main() { char a[="I am a boy,",b[20].*p1,*p2;p1=a;p2=b; //P1 and P2 point to the first element in array a and array b respectively for(;*p1!='\0';p1++,p2++) //p1,p2 add 1 each time *p2=*p1; . //Assign the value of the element pointed to by p1 to the element pointed to by p2 *p2='\0'; //Add "\ 0" after copying all valid characters printf("string a is:%s\n",a); //Output a the characters in the array print("string b is:%s\n",b); //Within the characters in the output b array return 0; } //What is emphasized here is some functions realized by using the numerical addition property of the pointer itself
Arrays and pointers
One dimensional array
int array[10]; int *p; //The following operations are equivalent. They are OK by default and can be processed through the output format shown in the figure p = &array[0]; int *p = &array[0]; int *p = &array;
Index operator []
----For the array element a[i], a[i] actually refers to the ith element of the array a, which addresses the address I through [] and obtains data. a[i] is equivalent to * (a+i)
----Pointers to arrays can also be used directly * (p+i)=p[i]=a[i]=*(a+i)
Pointer and string
//Strings can also be represented directly using pointers char * string; string = "I am C" printf("%s",string);
----The character pointer variable can be assigned, but the array name [address of the first element of the array] cannot be assigned
----The value of the pointer variable can be changed, but the array character name cannot
----The element value in the character array can be changed, but the value of the character pointer variable cannot be changed
----Clever use of pointer variable in printf: instead of formatting statement
char *format= "a=%d,b= %f\n"; printf(format,a,b);
Pointer summary
meaning | definition |
---|---|
int i; | Define integer variable i |
int *p; | p is a pointer variable pointing to integer data |
int a[n]; | Defines an integer array a with n elements |
int *p[n]; | Pointer array p composed of n pointer variables pointing to integer data |
int(*p)[n]; | p is a pointer variable to a one-dimensional integer array containing n elements |
int f(); | f is a function that returns an integer number |
int *p(); | p is a function that returns a pointer to an integer data |
int (*p)(); | p is the pointer variable to the function, which returns an integer number |
int **p; | p is a pointer variable that points to a pointer variable that points to integer data |
Chapter 8 structural programming
Basic knowledge
structural morphology
----Integrate different types of data into a whole
Structure - Definition
struct student { int num; char name[20]; char sex; int age; float score; char addr[30]; }; struct student stu1 stu2; //-----------------Split line--------------------- struct student { int num; char name[20]; char sex; int age; float score; char addr[30]; }stu1 ,stu2; //-----------------Split line--------------------- struct { int num; char name[20]; char sex; int age; float score; char addr[30]; }stu1 ;
----The above three methods are all used to define a structure. The first is a segmented definition, the second is a definition based on the structure name at the same time, and the third is that when a structure is defined as nameless, only one name can be given to the nameless structure.
Structure - Reference
stu1.num = 10; stu1.score = 99;
Structure nesting
struct student { int num; char name[20]; struct date { int month; int day; int year; }birthday; }stu1 ,stu2; stu1.birthday.month = 12;
Structure - initialization
struct { int num; char name[20]; char sex; int age; float score; char addr[30]; }stu1 ; struct student stu1={112,"Wang Lin",'M',19,"200 Beijing Road"}; //-----------------Split line--------------------- struct { int num; char name[20]; char sex; int age; float score; char addr[30]; }stu1 ={112,"Wang Lin",'M',19,"200 Beijing Road"};
Structure array
struct student { int num; char name[20]; char sex; int age; }stu[3];//Use array indexes to integrate multiple structures at the same time //-----------------Split line--------------------- struct student stu[]={{100,"Wang Lin",'M',20},{101,"Li Gang",'M',19},{110,"Liu Yan",'F',19}};
Structure - pointer
struct student { int num; char name[20]; char sex; int age; }stu; struct student *p=&stu; //Create a pointer to the stu structure stu.num = 101 Equivalent to (*p).num=101
----Use the members of structure variables as parameters
----Using structural variables as parameters - value transfer, low efficiency - in fact, I don't understand why I think the efficiency of using variables is lower
----The pointer to the structure variable is used as the parameter - address transfer
Linked list
----Classic format
struct student { int num ; char name[10]; struct student *next; }
Development of dynamic storage
a = malloc(100);//Open up an area with a size of 100 bytes and return the address of the first byte of the value bit; If the return value is empty, it indicates that there is insufficient memory space and cannot be created successfully p=(int *)malloc(n*sizefint)//Examples commonly used //malloc does not initialize the requested space //calloc initializes the requested space to 0
free
int *p free(p) //Used to release the memory corresponding to the pointer
realloc()
//Dynamically resize memory realloc(void *p,int newsize); //Adjust the corresponding memory through the pointer to adjust the memory to the size of new size
Common body
----Make different types of variables coexist in a section of memory, next to each other
----Some rules:
--------Common body variables cannot be referenced directly, but their members can be referenced
--------When defining variables, internal members need to be defined one by one through the index
--------Other variables can be assigned using the entire community variable – eg.a = union
Basic structure
//Basic structure union data { int i; char ch; float f; };
Shared internal variable reference
union data { int i; char ch; float f; }; union data a,b,c,*p,d[3]; //How arrays are referenced a.ch a.i a.f p->i p->ch p->f (*p).i (*p).ch (*p).f d[0].i d[0].ch d[0].f //-->Note that the index 0 to be used here starts with the address number
Some attention
----The storage mode of structure and common body is different, and they can be nested with each other
----The variable address of a community and the addresses of its members are the same address
----A value cannot be obtained by using the variable name of a common body, and the variable name of a common body cannot be assigned
Enum enum
----If a variable has only a set of possible values, it can be defined as an enumeration type. The so-called "enumeration" refers to listing the possible values one by one
enum Weekday{sun,mon,tue,wed,thu,fri,sat}; //Enum types begin with enum. The elements in curly braces are called enum elements or enum constants //It can also be defined in a similar way to the structure enum {sun,mon,tue,wed,thu,fri,sat}workday,weekend; //The default values are sun=0,mon=1,tue=2,wed=3,thu=4,fri=5,sat=6 - - this type is mainly used to facilitate code reading - - you can also modify the value by force -- > enum {sun=1,mon,tue,wed,thu,fri,sat}workday,weekend; //Now sun=1,mon=1,tue=2,wed=3,thu=4,fri=5,sat=6
typedef
----Used to alias variable types
----Is to alias an existing type without actually creating a new type
----Simplify programming difficulty
----#define performs simple character replacement during precompiling, while typedef is processed in the compilation stage, not simple character replacement
----You can declare multiple data types in one file, and then use #include instruction to include them in other files to simplify programming difficulty
typedef int int_Leon; int_Leon a; //Declared -- a new type name Date, representing the structure type typedef struct { int month; int day; int year; }Date; //Define the structure type variable birthday. Do not write it as struct Date birthday; Date birthday; //Defines the structure pointer variable p, which points to the structure type data Date*p; typedef int Num[100]; // Declaring Num as an integer array type name Num a;//Define a as the integer array name, which has 100 elements //Declare String as character pointer type typedef char* String; //Define p as character pointer variable and s as character pointer array String p,s[10]; // Declare Pointer as the Pointer type to the number of Li. This function returns an integer value typedef int (* Pointer)(); Pointer p1,p2;// The Pointer with P1 and P2 of type Pointer becomes the most important
Chapter IX document program design
Basic knowledge
file
**Program files: * * include source program files (suffix c), target files (suffix. obj), executable files (suffix. exe), etc. The content of this file is program code.
**Data file: * * the content of the file is the data for processing when the program runs
A
----In order to simplify the user's operation of input and output devices, the operating system treats all kinds of devices as files. From the perspective of the operating system, each input and output device connected to the host is regarded as a file. For example, the terminal keyboard is an input file, and the display screen and printer are output files.
----File generally refers to the collection of data stored on external media. The operating system manages the data in the unit of file.
----Input and output is the process of data transmission. Data flows from one place to another like water. Therefore, input and output are often vividly called stream, that is, data stream. Flow represents the flow of information from source to destination.
----During the input operation, the data flows from the file to the computer memory, and during the output operation, the data flows from the computer to the file (such as printer, disk file).
----C language regards a file as a sequence of characters (or bytes), that is, it is composed of a data sequence of characters (or bytes).
----The start and end of the input / output data stream are only controlled by the program and not by physical symbols (such as carriage return and line feed), which increases the flexibility of processing. Such files are called streaming files.
File save path
----A file should have a unique file ID so that users can identify and reference it
----File identification includes three parts: (1) file path; (2) File name backbone; (3) File suffix – > D: \ CC \ temp \ file1 dat
----The file path represents the location of the file in the external storage device.
----The file suffix is used to indicate the nature of the file.
----For convenience, the file ID is often called the file name, but it should be understood that the file name at this time actually includes the above three parts, and
Not just the file name trunk.
file store
----Data files can be divided into ASCII files and binary files.
----Data is stored in binary form in memory,
----If it is required to store in ASCII code on external memory, it needs to be converted before storage. ASCII files, also known as text files, store the ASCII code of one character per byte.
----When outputting in ASCII code, bytes correspond to characters one by one, and one byte represents one character, so it is convenient to process characters one by one and output characters. However, it generally occupies more storage space and takes conversion time (conversion between binary form and ASCII code). Outputting values in binary form can save external memory space and conversion time, and output the contents of the storage unit in the memory intact to the disk (or other external media). At this time, each byte does not necessarily represent a character.
file buffer
----ANSIC standard uses "buffer file system" to process data files. The so-called buffer file system means that the system automatically opens up a file buffer for each file in use in the program in the memory area. - ------ data output from memory to disk must be sent to the buffer in memory first, and then sent to the disk together after filling the buffer.
----If data is read from the disk to the computer, a batch of data is input from the disk file into the memory buffer at one time (filling the buffer), and then the data is sent one by one from the buffer to the program data area (to the program variable).
----This is to save access time and improve efficiency. The size of the buffer is determined by each specific C compilation system.
field name pointer
The used File will open up a corresponding File information area in memory to store the relevant information of the File, which is stored in a structure variable. The structure is declared by the system and named File;
typedef struct { short level; //The extent to which the buffer is "full" or "empty" unsigned flags; //File status flag char fd; //File descriptor unsigned char hold; //If there is no content in the buffer, do not read characters short bsize; //Buffer size unsigned char*buffer; //Location of data buffer unsigned char*curp; //The current point of the file location marker pointer unsigned istemp; //Temporary file indicator short token; //For validity check }FILE; //-Stdio, a C compilation environment H header file has the following file type declaration FILE *fp//Define a pointer variable pointing to FILE type data, which is a structure variable. You can access the FILE and obtain internal information by changing the amount; This pointer is called a pointer variable to a FILE; It refers to the first pointer of the FILE information area, not the beginning of the data FILE on the external media
File opening and closing
A
----The open value is to establish corresponding file information area [used to store information about files] and file buffer [used to temporarily store input and output data] for files
----Use a pointer and a structure to complete related operations
----Closing refers to revoking the file information area and file buffer so that the file pointer variable no longer points to the file. Obviously, it is impossible to read and write the file
Related operations
//fopen open data file FILE &fp; a = fgetc(fp) //Gets one character, and the return value is one character fp = fopen("a1","r");//The return value is a pointer to the a1 file information area fgets(str,n,fp) //Get a string of characters with length of n-1 and save it to str, and return the value of the first element of str array fputc(ch,fp)//Write a ch character to the file. If the output is successful, the output character is returned. If it fails, the EOF is returned, that is - 1 fputs(str,fp)//Write the string of str to the file pointer variable fp; 0 is returned if the output is successful, otherwise - 1 is returned fprintf(fp,"%d %d",i,f);//Import into a file in the specified format fscanf(fp,"%d %d",&i,&f);//Gets the value from the file in the specified format //Judge whether the file is read to the end while((ch=fgetc(fp))!=EOF)//EOF=-1. After reading, it returns - 1 while(!feof(fp))//A non-zero value is returned when the file ends, and 0 when it does not end
Document processing method | meaning | The specified file does not exist |
---|---|---|
"r" (read only) | To enter data, open an existing text file | report errors |
"W" (write only) | To output data, open a text file | To output data, open a text file and create a new file |
"a" (added) | Add data to the end of a text file | error |
"rb" (read only) | To enter data, open a binary file | error |
"wb" (write only) | To output data, open a binary file | Create new file |
"ab" (additional) | Add data to the end of a binary file | error |
"r +" (read / write) | To read and write, open a text file | error |
"w +" (read / write) | Create a new text file for reading and writing | Create new file |
"a +" (read / write) | To read and write, open a text file | error |
"rb +" (read / write) | To read and write, open a binary file | error |
"wb +" (read / write) | Create a new binary file for reading and writing | Create new file |
"ab +" (read / write) | Open a binary file for reading and writing | error |
----fgets and fputs take the specified file as the read-write object, while gets and puts take the terminal as the read-write object
Format read / write
fprintf(fp, "%d.,6.2f",i,f); //Output the values of int type variable i and float type variable f to the file pointed to by fp in the format of% d and% 6.2f fscanf (fp,"%d,6f" ,&i,&f);//Disk file If there is a character "3,4.5", read the integer 3 from it and send it to the integer variable i, and read the real number 4.5 and send it to the float variable f
Binary reading and writing
//----C language allows you to use the fread function to read a data block from the file and the fwrite function to write a data block to the file. //----When reading and writing, it is in binary form. //----When writing data to the disk, directly copy a group of data in the memory to the disk file intact without conversion / / and read several bytes of the disk file into the memory in batches //Note: if the function is executed successfully, the return value is a formal parameter fread(buffer, size, count, fp); fwrite(buffer, size, count, fp); buffer,Is an address that stores the starting address of the file read data area; size The number of bytes to read and write, count The number of data items to be read and written. The length of each data item is size fp: FILE Type pointer a = fread(f,4,10,fp);
Random reading and writing
----Read and write files at any location to improve efficiency
//rewind() causes the file location tag to point to the beginning of the file //Rewind (file pointer); //The rewind function returns the file location mark to the beginning of the file. This function does not return a value. //Changing the file location mark with the fseek function //"Start point": replace with 0, 1 or 2. 0 represents "file start position", 1 is "current position", 2 is "file end position". Use numerical value to mark the initially defined position //Fseek (file type, pointer, displacement, starting point); //"Displacement": refers to the number of bytes moved forward based on the starting point (long integer) //The fseek function is generally used for binary files. fseek (fp,100L,0);//Move the file location mark forward to 100 bytes from the beginning of the file fseek (fp,5OL,1);//Move the file location mark forward 50 bytes from the current location fseek (fp.-10L,2);//Move the file location mark back 10 bytes from the end of the file //Using ftell function to determine the current position of file location mark //The ftell function is used to get the current position of the file position mark in the streaming file, expressed by the displacement relative to the beginning of the file. If there is an error when calling the function (for example, there is no file pointed to by fp), the return value of the fill function is - 1L. i=ftell(fp);//Current location of variable i storage file if(i==-1L) print(" error\n"); //For example, "error" is output if there is an error when calling the function
Error detection of file reading and writing
ferror(fp);
When calling various functions for processing, you can use ferror to check. The return value of 0 indicates that there is no error, otherwise an error has occurred. At this time, you should use clearerr(fp) or rewind to clear the error value of 0 for the next detection