当前位置:网站首页>C basic (VII) document operation
C basic (VII) document operation
2022-07-04 04:53:00 【mChenys】
Catalog
- One 、 Opening and closing of files
- Two 、 Read and write characters
- 2.1 getc function
- 2.2 putc function
- 2.3 Case study - Realize the console input file name to create a file and support the write function
- 2.4 Case study - Implement the console to input the file name and read the contents of the file
- 2.5 Case study - Realization echo The function of
- 2.6 Case study - Realize the command of file copy
- 2.7 Realize file encryption and decryption
- 2.8 EOF And feof End of function file
- 3、 ... and 、 Read and write a line of text
- 3.1 fprintf and fscanf function
- 3.2 Case study - Print the contents entered by the user console into a file
- 3.3 fgets and fputs function
- 3.4 Case study - Realize file copy
- 3.5 The basis of file copy is to add encryption and decryption operations
- 3.6 Case study - Realize big data sorting
- 3.7 Case study - Realize four operations in reading source files , After reading, you need to fill in the results and update the source file
- 3.8 Case study - Text content in a given format , Take out the name of the second oldest person inside
- Four 、 Get the properties of the file
- 5、 ... and 、 Read and write text and binary
- 6、 ... and 、 Use of other auxiliary functions
- 7、 ... and 、 Comprehensive case - Realize a student information input and query program
One 、 Opening and closing of files
1.1 fopen function
FILE *fopen(const char*path,const char*mode);
fopen If the file is opened successfully, a valid FILE Address , Failure returns NULL
path Is to specify the path to open the file , Can be a relative path , It could be an absolute path .
Pattern (mode) There are the following :
- r: Open the file read-only , The file must exist , And the permission to read ;
- rb: Open a binary file in read-write mode , The file must exist and need to be read ,b Options in windows It works ,windows All text is \r\n At the end of the , instead of \n At the end of the , If you don't bring it when reading the file b, Then the system will automatically \r eat ;
- r+: and r similar , But it can also write files ( The premise is that the file must exist );
- w: Open write only , If the file exists, the file length is clear 0, That is, the contents of the file will disappear , If the file does not exist, create the file , Write permission required , stay windows It will automatically be on \n Front supplement \r;
- w+: and w similar , But it can also read files ;
- wb: stay Windows Effective under , It can avoid the system automatically in \n Add before \r character ;
- a: Open the write only file as an append , If the file does not exist , The file will be created , If the file exists , The data written will be added to the end of the file , That is, the original contents of the document will be preserved .(EOF Fu reserved ), Write permission required ;
- a+: and a similar , Can read and write at the same time
among b Option means binary , It can be combined with all the above patterns .
Be careful : stay windows Read and write a secondary file , Generally, we need to add b, Prevent the system from adding fearless \r; But if you are reading and writing a text file , Then don't add b, So you don't have to deal with this alone \r.
stay Windows In the system , In text mode , Document to "\r\n" On behalf of the line , If you open a file in text mode , And use fputs Wait for the function to write the newline character "\n" when , The function will automatically be in "\n" The front is added with "\r". That is, what is actually written to the file is "\r\n".
In the class unix/linux In the text mode of the system , The file is "\n" For line feed , therefore linux There is no difference between the text mode and binary mode of the system .
1.2 fclose function
Close open files , and fopen Matching use of , as long as fopen Successfully returns , So you need to call that fclose Release resources .
fclose(FILE *stream);
Two 、 Read and write characters
2.1 getc function
Read character
int getc(FILE *stream);
getc The parameter of is a fopen Pointer returned after successfully opening the file ,getc Back to a char, Its function is to read the contents of the file in bytes , The final end mark of the text file is -1, That's one EOF Macro definition #define EOF -1
#include <stdio.h>
int main()
{
FILE *fp = fopen("user.txt", "r");
char c;
while ((c = getc(fp)) != EOF) // Read every character of the file , Till the end
{
printf("%c", c);
}
fclose(fp);
return 0;
}
2.2 putc function
The output characters
int putc(int c,FILE *stream);
Parameters 1 Is to be written char, Parameters 2 yes fopen File pointer returned .
#include <stdio.h>
#include <string.h>
int main()
{
FILE *fp = fopen("a.txt", "w");
const char *s = "hello world";
int i;
for (i = 0; i < strlen(s); i++)
{
putc(s[i], fp); // Write data to file
}
putc('\n', fp); // Add line breaks
fclose(fp);
return 0;
}
C In language fgetc、fputc and getc、putc What's the difference ?
Never think of fgetc、fputc Of f It stands for file, These two functions are related to files ! Have to look at their function declarations , Here's the picture :
You see , Parameters are acceptable FILE Pointer , Actually that f What it represents is function.fgetc and getc Their difference is not in their use , But in their implementation ! say concretely , Just take f Of (fgetc、fputc) It is implemented through functions , Without f(putc、getc) Of , It is implemented through macro definition ! About their differences , take getc and fgetc Come on :
- getc The argument to should not be an expression with side effects .
- because fgetc It must be a function , So you can get its address . This allows for fgetc The address of is passed to another function as a parameter .
- call fgetc It is likely to take longer than calling getc, Because calling a function usually takes longer than calling a macro .
2.3 Case study - Realize the console input file name to create a file and support the write function
The renderings are as follows :
Open the target file
Code up :
#include <stdio.h>
int main(int argc, char **args)
{
if (argc < 2)
return 0;
FILE *fp = fopen(args[1], "w");
if (fp)
{
while (1)
{
printf(" Loop start --\n");
char c = getchar(); // Read one at a time from the standard console char, Including carriage returns
printf(" received %c\n", c);
if (c == '0')
break;
putc(c, fp);
printf("-- The loop ends \n");
}
fclose(fp);
}
return 0;
}
2.4 Case study - Implement the console to input the file name and read the contents of the file
The renderings are as follows :
#include <stdio.h>
int main(int argc, char **args)
{
if (argc < 2)
return 0;
FILE *fp = fopen(args[1], "r"); // Read according to the path entered by the user
if (fp)
{
char c;
while ((c = getc(fp)) != EOF)
{
printf("%c", c);
}
fclose(fp);
}
return 0;
}
2.5 Case study - Realization echo The function of
design sketch :
see a.txt The contents of the document are as follows :
#include<stdio.h>
#include<string.h>
int main(int argc,char **args)
{
if(argc <2)
return 0;
char *s = args[1]; // String content
char *op = args[2]; // > or >> , Note that console input needs to be escaped , \> perhaps \>\>
FILE *fp = NULL;
if(strcmp(">",op)==0)
fp = fopen(args[3],"w"); // newly build
if(strcmp(">>",op)==0)
fp = fopen(args[3],"a"); // Additional
if(fp)
{
int i;
for(i = 0;i<strlen(s);i++)
{
putc(s[i],fp);
}
putc('\n',fp);// Add new lines to the end
fclose(fp);
}
return 0;
}
perhaps
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char **args)
{
if (argc != 4)
{
printf("Usage: test \"hello\" > a.txt");
return -1;
}
char *content = args[1];
char *op = args[2];
char *path = args[3];
FILE *f = NULL;
if (strcmp(op, ">") == 0)
{
f = fopen(path, "w");
}
else if (strcmp(op, ">>") == 0)
{
f = fopen(path, "a");
}
else
{
printf("Unknow option:%s\n", op);
return -1;
}
if (f)
{
int size = strlen(content);
for (int i = 0; i <= size; i++) // Be careful : It contains size, So at the end of the string '\0' It can also output
{
putc(content[i], f);
}
//putc('\n',f);// Add new lines to the end
fclose(f);
}
return 0;
}
2.6 Case study - Realize the command of file copy
#include<stdio.h>
int main(int argc, char **args)
{
if (argc != 3)
{
printf("Usage:test a.txt b.txt");
return -1;
}
FILE *src = fopen(args[1], "r");
FILE *dst = fopen(args[2], "w");
if (src && dst)
{
char c;
while ((c = getc(src)) != EOF)
{
putc(c, dst);
}
fclose(src);
fclose(dst);
}
return 0;
}
2.7 Realize file encryption and decryption
#include <stdio.h>
#include <string.h>
int main(int argc, char **args)
{
if (argc != 4)
{
printf("Usage: pwd a.txt b.txt 0\n0: encryption \n1: Decrypt \n");
return -1;
}
FILE *src = fopen(args[1], "r");
FILE *dst = fopen(args[2], "a");
char *op = args[3]; // It can also be used here args[3][0] Take characters to compare
if (src && dst)
{
char c;
while ((c = getc(src)) != EOF)
{
if (strcmp(op, "0") == 0)
{
// encryption
c++;
}
else if (strcmp(op, "1") == 0)
{
// Decrypt
c--;
}
putc(c, dst);
}
fclose(src);
fclose(dst);
}
return 0;
}
2.8 EOF And feof End of function file
How can the program know whether it has reached the end of the file ?EOF Represents the end of the file , If it is already at the end of the file , that feof The function returns true, and EOF The value is -1, When reading a text file, you can judge whether the characters read are EOF Or call feof return true It means the end of the file is read , But to judge binary files, you must use feof Function to determine . Because of the character ASCII The code can't be EOF(-1), But it is possible that binary files are binary numbers -1 Of , So binary files can only be used feof Function to determine .
int feof(FILE *stream);
3、 ... and 、 Read and write a line of text
3.1 fprintf and fscanf function
this 2 Functions all pass through FILE * To text file ( character ) Read and write lines ( Every time it's an operation That's ok data ), But it cannot be used to operate binary files ( Executable program , Music, etc ).
int fscanf(FILE *stream, const char *format, ...); // and sscanf Function as , The difference is to extract and parse from the file
int fprintf(FILE *stream, const char *format, ...);// and sprintf Function as , The difference is to output to the file
3.2 Case study - Print the contents entered by the user console into a file
#include<stdio.h>
#include<string.h>
int main()
{
FILE *wf = fopen("a.txt","w");
char buf[1024] = {
0};
while(1)
{
scanf("%s",buf);
if(strcmp("exit",buf) ==0)
break;
fprintf(wf,"%s\n",buf);// Output to a file in the specified format
}
fclose(wf);
return 0;
}
3.3 fgets and fputs function
this 2 Functions can be used together , Read and write one string at a time .
char *fgets(char *s, int size, FILE *stream); // Read one line of string at a time , Include line breaks
int fputs(const char *s, FILE *stream); // Output one line of string at a time
The following is how to input content from the console and save it in a file
#include <stdio.h>
#include <string.h>
int main(int argc, char **args)
{
if (argc < 2)
return 0;
FILE *wf = fopen(args[1], "w");
while (1)
{
char buf[1024] = {
0};
fgets(buf, sizeof(buf), stdin); // Read data from the console to buf in , Be careful fgets You can also read from a file , The third parameter is changed to FILE * that will do
if (strncmp(buf, "exit", 4) == 0)
break;
fputs(buf, wf); // Write to file
}
fclose(wf);
return 0;
}
3.4 Case study - Realize file copy
#include<stdio.h>
int main(int argc,char **args)
{
if(argc < 3)
return 0;
FILE *rf = fopen(args[1],"r");
FILE *wf = fopen(args[2],"w");
if(rf)
{
while(!feof(rf))// As long as it doesn't reach the end of the file , The cycle continues
{
char buf[1024] = {
0};
fgets(buf,sizeof(buf),rf);// Read from file
fputs(buf,wf);
}
fclose(rf);
fclose(wf);
}
return 0;
}
3.5 The basis of file copy is to add encryption and decryption operations
#include<stdio.h>
// encryption
void encode(char *s)
{
int len =0;
while(s[len])
{
s[len++]++; // String each char Move one bit to achieve encryption
}
}
// Decrypt
void decode(char *s)
{
int len=0;
while(s[len])
{
s[len++]--;// String each char Step back to decrypt
}
}
int main(int argc,char **args)
{
if(argc < 3)
return 0;
FILE *rf = fopen(args[1],"r");
FILE *wf = fopen(args[2],"w");
char op = args[3][0]; // Encryption and decryption operators
if(rf)
{
while(!feof(rf))// As long as it doesn't reach the end of the file , The cycle continues
{
char buf[1024] = {
0};
fgets(buf,sizeof(buf),rf);// Read from file
if(op == '0')
encode(buf);
else
decode(buf);
// Write to target file
fputs(buf,wf);
}
fclose(rf);
fclose(wf);
}
return 0;
}
3.6 Case study - Realize big data sorting
Suppose there's a file , It's full of data 0~255 The random number , The total size is 1G many , How to sort the data in the file quickly ?
Ideas : First, using bubble sorting is not feasible , Because the stack memory is limited , The size of the array cannot be defined too large , And it's less efficient . So we have to change our thinking , Because the data is all 0~255 Data and 1G many , It can be seen that there will be a lot of duplicate data , So you can define a 255 Array of elements , Just record the number of times each random number appears , And the array subscript is the sorting of random numbers . After the statistics are completed, the sorting is automatically completed .
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#include<string.h>
void makeRand(char *path,int count) // Generate random number
{
FILE * wf = fopen(path,"w");
int t = (int)time(NULL);
srand(t);
int i;
for(i=0;i<count;i++)
{
int i = rand()%256;
char buf[4] = {
0};
sprintf(buf,"%d\n",i);// Save random numbers into an array
fputs(buf,wf);// Then write the array to the file
}
fclose(wf);
}
int main(int argc,char **args) // Sort the contents of the file
{
if(argc <2 )
return 0;
char *op = args[2];
if(strcmp("make",op) ==0)
makeRand(args[1],atoi(args[3])); // Generate random number
else
{
int arr[256] = {
0}; // Store sorted
FILE *rf = fopen(args[1],"r");
while(!feof(rf))
{
char buf[4]={
0};
fgets(buf,sizeof(buf),rf); // Read random from the file into the character array
int i = atoi(buf);// String to number
arr[i]++; // Count the number of occurrences and automatically sort , Subscripts are random numbers , from 0~255 Automatic sorting
}
fclose(rf);
// Overwrite the sorted results with the source file
FILE *wf = fopen(args[1],"w");
int i,j;
for(i = 0;i < 256;i++) // At most 256 A random number ,i Represents random number
{
for(j= 0 ;j<arr[i];j++) // Output for each random number j Time
{
// Number to string
char buf[4] = {
0};
sprintf(buf,"%d\n",i);
// output to a file
fputs(buf,wf);
}
}
fclose(wf);
}
return 0;
}
3.7 Case study - Realize four operations in reading source files , After reading, you need to fill in the results and update the source file
For example, the contents of the source file are as follows :
2+2
2*3
3/3
5-3
After execution , The source file needs to be modified as follows :
2+2=4
2*3=6
3/3=1
5-3=2
Ideas : You need to read the source file first , After reading each line of string, pass sscanf Read the modified string , Take out each operation variable and operator, perform four operations, and save the results , Then use sprintf Output the expression with the result of the operation to a temporary character array , Then dynamically allocate memory in the heap to create strings, and append each temporary character array to the string , Finally, you can overwrite the source file with this string .
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int doCale(int i, int j, char c)
{
int result = 0;
switch (c)
{
case '+':
result = i + j;
break;
case '-':
result = i - j;
break;
case '*':
result = i * j;
break;
case '/':
result = i / j;
break;
}
return result;
}
int main()
{
FILE *rf = fopen("a.txt", "r");
int lineCount = 1; // Record the number of lines
char *s = NULL; // Dynamic update results
while (1)
{
// The source file reads the result one line at a time
char buf[16] = {
0};
fgets(buf, sizeof(buf), rf); // Read the last line ,feof Will not return immediately true
printf(" Read the second %d Line string :%s", lineCount, buf);
// Parse the value of the expression
int i, j;
char c;
sscanf(buf, "%d%c%d", &i, &c, &j);
// The result of the calculation is
int result = doCale(i, j, c);
// A row of data containing the result
char result_buf[16];
sprintf(result_buf, "%d%c%d=%d\n", i, c, j, result);
printf(" Operation expression :%s", result_buf);
// Dynamic application heap space
s = (char *)realloc(s, sizeof(result_buf) * lineCount);
// Append the result to s in
strcat(s, result_buf);
lineCount++;
if (feof(rf))
{
printf("\n Read to the end of the file \n");
break; // It's the last line , Adjust again feof Will return true
}
}
// close the source file
fclose(rf);
// Now start updating the source file
FILE *wf = fopen("a.txt", "w");
fputs(s, wf); // Output s The content in
fclose(wf);
// Release space
free(s);
return 0;
}
The operation results are as follows :
3.8 Case study - Text content in a given format , Take out the name of the second oldest person inside
For example, the text is as follows :
full name =aaa, Age =20
full name =bbbb, Age =18
full name =ccc, Age =30
full name =ddd, Age =19
The implementation code is as follows :
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// The structure used to encapsulate each row of data
struct man
{
char *name;
int age;
};
int main()
{
struct man *p = NULL; // Define structure pointer
FILE *rf = fopen("a.txt", "r"); // Read the target file
int index = 1;
while (1)
{
char buf[1024];
fgets(buf, sizeof(buf), rf); // Read each row of data , Deposit in buf in
if (feof(rf))
break;
// char name[100];
// int age =0;
// sscanf(buf," full name =%s, Age =%d",name,&age); There will be problems in parsing directly like this , It will bring = The ones after the number are all matched with names
// printf("name=%s,age=%d\n",name,age);// Output name= All the rest , and age=0, obviously sscanf This format cannot be parsed
// Dynamic memory allocation
p = realloc(p, sizeof(struct man) * index);
// First, divide the string of each line by commas
char *s;
s = strtok(buf, ","); // Get the... Before the comma full name =xxx ,s The pointer now points to ' surname ' The address of this character
s = &s[7]; // Take out the name after the equal sign , s[7] Indicates positioning to 7 Characters , And then through & Take its address and assign it to s, such s The first address pointed to by the pointer becomes = The address of the first character after the number , " full name =" It happens to occupy 7 Bytes
// name Members are pointer variables , You need to initialize
p[index - 1].name = malloc(strlen(s) + 1);
strcpy(p[index - 1].name, s);
s = strtok(NULL, ",");
s = &s[7]; // Take out the age , take s Point to 7 Byte address , " Age =" It happens to account for 7 Bytes
p[index - 1].age = atoi(s); // The extracted age is of string type , It needs to be converted into int
index++;
}
// Close file
fclose(rf);
// Sort the structure , Bubble sort is used here
int i, j;
int size = index - 1;
for (i = 0; i < size; i++)
{
for (j = 0; j < size - i - 1; j++)
{
if (p[j].age > p[j + 1].age)
{
struct man tmp = p[j];
p[j] = p[j + 1];
p[j + 1] = tmp;
}
}
}
// Take the name of the second oldest person
printf(" The second oldest name=%s\n", p[size - 2].name);
// Free memory
for (i = 0; i < size; i++)
{
free(p[i].name);
}
free(p);
return 0;
}
Four 、 Get the properties of the file
Use stat Function can get the attributes of the file , Including the establishment time of the document , Size and so on , Import required 3 Head file ,<sys/stat.h>,<sys/types.h>,<unistd.h>
int stat(const char * _Filename, struct stat * _Stat)
Parameters 1: For file name
Parameters 2:struct stat Structure
#include<stdio.h>
#include<sys/stat.h>
#include<sys/types.h>
#include<unistd.h>
int main()
{
struct stat st;
stat("a.txt",&st);
int size = st.st_size; // Get the size of the file
long time = st.st_atime; // Get the time of the last visit
printf("size=%d,time=%ld\n",size,time);
return 0;
}
The output is as follows :
size=87,time=1644801698
5、 ... and 、 Read and write text and binary
Use fwrite and fread this 2 Functions can manipulate files in binary form , Not limited to text files
size_t fread (void *buffer, size_t size, size_t count, FILE *stream) ;
size_t fwrite(const void* buffer, size_t size, size_t count, FILE* stream);
Parameters 1: Pointer variables of any type
Parameters 2: How many bytes does the size of each unit occupy , adopt sizeof Get the number of bytes occupied by the type
Parameters 3: How many units are read and written in total
Parameters 4:fopen File pointer returned
Just parameters 2* Parameters 3 The size of is equal to the parameter 1 The size of the memory area referred to is the same .
Return successful reading / Written Number of units
, Will be subject to parameters 2 Influence , When parameters 2 by 1 When , It can be considered that the returned value is read / Bytes written
5.1 fwrite function
Used to write binary data
#include <stdio.h>
int main()
{
FILE *wf = fopen("a.dat", "w");
int a = 10;
int size = fwrite(&a, sizeof(a), 1, wf); // Write one to the file 10, The corresponding binary is 0b1010
fclose(wf);
printf("size=%d\n", size); // size =1, It means that 1 individual sizeof(a)
return 0;
}
The file size of the production layer is 4 Bytes .
5.2 fread function
For reading binary files , Parameters and fwrite equally , It just becomes reading .
#include <stdio.h>
int main()
{
FILE *rf = fopen("a.dat", "r");
int a;
int size = fread(&a, sizeof(a), 1, rf);
// Output decimal numbers
printf("a=%d,size=%d\n", a, size); // a=10,size=1, Read it 1 individual sizeof(a)
fclose(rf);
return 0;
}
5.3 Case study - use fread/fwrite Realize binary number copy one by one
#include<stdio.h>
int main(int argc,char **args)
{
if(argc < 2)
return 0;
FILE *rf = fopen(args[1],"rb"); //b Option indicates binary mode operation
if(rf == NULL)
return 0;
FILE *wf = fopen(args[2],"wb"); //b Option indicates binary mode operation
if(wf == NULL)
return 0;
while(1)
{
char c = 0;
fread(&c,1,1,rf); // Read one byte at a time
if(feof(rf))
break;
fwrite(&c,1,1,wf); // Read one byte at a time
}
fclose(rf);
fclose(wf);
return 0;
}
The above code can not only be used to operate binary files , You can also operate ordinary text files
5.4 Case study - Use fread/fwrite Realize batch copy of binary data
#include<stdio.h>
#include<stdlib.h>
#include<sys/stat.h>
#define MAX 64*1024 //64k The maximum number of bytes in a single copy
int main(int argc,char **args)
{
if(argc < 2)
return 0;
FILE *rf = fopen(args[1],"rb");
if(rf == NULL)
return 0;
FILE *wf = fopen(args[2],"wb");
if(wf == NULL)
return 0;
int count =0;// Count the number of copies
// Get the file size
struct stat st;
stat(args[1],&st);
long size = st.st_size;
if(size >= MAX)
size = MAX;
// Define buffer
char* buf = malloc(size);
while(!feof(rf))
{
int len = fread(buf,1,size,rf); // Returns how many units have been read , Each unit is a byte
fwrite(buf,1,len,wf); // Write as many units as you read
count++;
}
fclose(rf);
fclose(wf);
free(buf);
printf("copy count=%d\n",count);
return 0;
}
5.5 Read and write structure data
The data of structure type is actually binary data
#include <stdio.h>
struct student
{
char name[30];
int age;
};
int main()
{
// Create an array of structs
struct student st[3] = {
{
"abc", 12}, {
"tom", 20}, {
"jack", 34}};
FILE *wf = fopen("st.dat", "w");
// Write the structure data to the file
fwrite(st, sizeof(struct student), 3, wf);
// If you want to write a single structure , It can be like this
fwrite(&st[0], sizeof(struct student), 1, wf);
fclose(wf);
// Read the structure from the file
FILE *rf = fopen("st.dat", "r");
struct student buf[4]; // Create an array of structs
fread(buf, sizeof(struct student), 4, rf);
fclose(rf);
int i;
for (i = 0; i < 4; i++)
printf("name=%s,age=%d\n", buf[i].name, buf[i].age);
return 0;
}
6、 ... and 、 Use of other auxiliary functions
6.1 fseek function
This function is used to set the file pointer stream The location of .
int fseek(FILE * _File, long _Offset, int _Origin);
The first parameter stream For file pointer
The second parameter offset For offset , A positive number indicates a positive offset , A negative number means a negative offset
The third parameter origin Set where to start the offset from the file , The possible value is :SEEK_CUR、 SEEK_END or SEEK_SET, The meaning is as follows :
SEEK_SET: Beginning of file
SEEK_CUR: The current position
SEEK_END: End of file
If it works ,stream Will point to with fromwhere Benchmarking , The offset offset( Pointer offset ) Byte position , The function returns 0. If the execution fails, do not change stream Point to , Function returns a non 0 value .
The experiment shows that , Beyond the end of the file , Or return 0. The back offset exceeds the first position , Or return 0, Please use with care .
#include <stdio.h>
int main()
{
char a[10] = {
1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
FILE *wf = fopen("a.dat", "w");
fwrite(a, 1, sizeof(a), wf);
fclose(wf);
FILE *rf = fopen("a.dat", "r");
fseek(rf, 2, SEEK_SET); // Move backward from the beginning of the file 2 Bytes , here rf The pointer of points to the number 3
char buf[2];
fread(buf, 1, sizeof(buf), rf);
printf("%d,%d\n", buf[0], buf[1]); // 3,4, here rf The pointer of points to the number 5
fseek(rf, -2, SEEK_CUR); // Go back from the current position 2 Bytes , above fread When curr Yes 5 The location of , So back off 2 Here we are again 3 Location.
fread(buf, 1, sizeof(buf), rf);
printf("%d,%d\n", buf[0], buf[1]); // 3,4 because FILE The pointer goes back 2 position
fseek(rf, 0, SEEK_SET); // Return to the beginning of the file
fread(buf, 1, sizeof(buf), rf);
printf("%d,%d\n", buf[0], buf[1]); // 1,2
fseek(rf, 0, SEEK_END); // Move to the end of the file
printf("%d,%d\n", buf[0], buf[1]); // 1,2 This output is actually buf The last data was not cleared , In fact, you can't read the content
fclose(rf);
return 0;
}
Use fseek Can quickly generate a large file
#include <stdio.h>
int main()
{
FILE *wf = fopen("a.dat", "w");
// int i;
// for(i=0;i<1000000;i++)
// {
// char a = 0;
// fwrite(&a,1,sizeof(a),wf);
// }
// You can use fseek Function implementation
fseek(wf, 9999999, SEEK_SET);
char a = 0;
fwrite(&a, 1, 1, wf);
fclose(wf);
return 0;
}
give the result as follows :
6.2 ftell function
function ftell Used to get the offset bytes of the current location of the file location pointer relative to the first file . When accessing files in random mode , Due to frequent back and forth movement of file locations , It's not easy for the program to determine the current location of the file .
FILE *fp = fopen("a.txt","r");
long len = ftell(fp)
skill : When fseek Move to the end of the file , Use ftell You can get the size of the file .
#include <stdio.h>
int main(int argc, char **args)
{
if (argc < 2)
return 0;
FILE *rf = fopen(args[1], "r");
if (rf)
{
fseek(rf, 0, SEEK_END); // First move to the end of the file
int len = ftell(rf); // Then get the pointer position , So you get the size of the file .
printf("file len is:%d\n", len);
}
return 0;
}
6.3 fflush function
c All file operation functions of the language are buffer functions , Only when the buffer is full Or called fclose Function before writing memory data to disk ,fflush Function can write any unwritten data in the buffer to a file . Successfully returns 0, Failure to return EOF.
int fflush(FILE * _File);
because fflush It is to write the contents of the buffer to the disk in real time , So don't use a lot .
6.4 remove function
remove Function to delete the specified file
int remove(const char *_Filename);
Parameters Filename For the specified file name to delete , If it is windows The following file name and path can be used with backslash \ Separate , You can also use slashes / Separate
6.5 rename function
rename Function to rename the specified file
int rename(const char *_OldFilename,const char *_NewFilename);
Parameters 1:_OldFilename For the specified file name to be modified .
Parameters 2:_NewFilename Is the modified file name , If it is windows The following file name and path can be used with backslash \ Separate , You can also use slashes / Separate .
7、 ... and 、 Comprehensive case - Realize a student information input and query program
The renderings are as follows :
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
struct student
{
char name[30];
int age;
};
int insert()
{
FILE *wf = fopen("st.dat", "a");
struct student st;
if (wf == NULL)
return 0;
while (1)
{
printf("please input name:");
scanf("%s", st.name);
if (strcmp("exit", st.name) == 0)
break;
printf("please input age:");
scanf("%d", &st.age);
fwrite(&st, sizeof(struct student), 1, wf); // Write to file
}
fclose(wf);
}
int search()
{
FILE *rf = fopen("st.dat", "r");
if (rf == NULL)
return 0;
struct student st;
char success = 0;
printf(" Please output the name to be queried , Input all Find all :");
char name[30];
scanf("%s", name);
while (1)
{
fread(&st, sizeof(struct student), 1, rf); // Read from a document
if (feof(rf))
break;
if (strcmp("all", name) == 0)
{
printf("name=%s,age=%d\n", st.name, st.age);
success = 1;
}
else if (strcmp(st.name, name) == 0)
{
printf("name=%s,age=%d\n", st.name, st.age);
success = 1;
break;
}
}
if (!success)
printf("not found\n");
fclose(rf);
}
int delete ()
{
FILE *rf = fopen("st.dat", "r");
if (rf == NULL)
return 0;
fseek(rf, 0, SEEK_END); // Move to the end of the file
int fileLenght = ftell(rf); // Get the total length of the file
int count = fileLenght / sizeof(struct student); // Calculate how many structures there are
fseek(rf, 0, SEEK_SET); // Reset pointer position
struct student *st; // Create structure pointer
st = malloc(count * sizeof(struct student)); // Allocate memory once
printf(" Please enter the name to delete :");
char name[30];
scanf("%s", name);
while (1)
{
fread(st, sizeof(struct student), count, rf); // Read from a document
if (feof(rf))
break;
}
fclose(rf);
FILE *wf = fopen("st.dat", "w");
int i;
for (i = 0; i < count; i++)
{
if (strcmp(st[i].name, name) == 0)
continue;
fwrite(&st[i], sizeof(struct student), 1, wf);
}
fclose(wf);
free(st);
}
int main(int argc, char **args)
{
if (argc < 2)
{
printf(" Please enter the second parameter , 1 Means new ,2 Represents a query ,3 Said to delete \n");
return 0;
}
else if (args[1][0] == '1')
insert();
else if (args[1][0] == '2')
search();
else if (args[1][0] == '3')
delete ();
return 0;
}
边栏推荐
猜你喜欢
Beipiao programmer, 20K monthly salary, 15W a year, normal?
软件设计文档示例模板 - 学习/实践
Create ASM disk through DD
VSCode的有用插件
Developing mqtt access program under QT
Many founders of technology companies provided enterpriser first with a round C financing of up to US $158million to help it invest in the next generation of global innovators
2022年6月总结
Technology Management - learning / practice
ADB tools
Kivy教程之 更改背景颜色(教程含源码)
随机推荐
【MATLAB】MATLAB 仿真模拟调制系统 — SSB 系统
浅谈JVM的那些事
LeetCode136+128+152+148
Annex VI: defense work briefing docx
20000 words will take you to master multithreading
【MATLAB】MATLAB 仿真数字基带传输系统 — 数字基带传输系统
1. Mx6u-alpha development board (simulating STM32 drive development experiment)
What is context?
What is the difference between Western Digital Green disk, blue disk, black disk, red disk and purple disk
Kivy tutorial custom fonts (tutorial with source code)
【MATLAB】MATLAB 仿真 — 模拟调制系统 之 AM 调制过程
【MATLAB】MATLAB 仿真模拟调制系统 — VSB 系统
关于solidworks standard无法获得许可 8544问题的总结
Binary search tree
cmake
appliedzkp的zkevm(12)State Proof
RAC delete damaged disk group
RPC Technology
Qt QTableView数据列宽度自适应
Kivy tutorial 07 component and attribute binding implementation button button click to modify the label component (tutorial includes source code)