当前位置:网站首页>[C language] 10000 word document operation summary
[C language] 10000 word document operation summary
2022-07-19 16:28:00 【Ordinary person 1】
author :@ Ordinary person 1
special column :《C Language from 0 To 1》
In a word : In the past , All is prologue
explain : The past is irreparable , The future can change
List of articles
file
It involves the problem of data persistence , Our general methods of data persistence are , Store the data in a disk file 、 Stored in the database .
Using files, we can store data directly on the hard disk of the computer , Data persistence is achieved .
The files on disk are files .
But in programming , There are two kinds of documents we usually talk about : Program files 、 Data files ( Classified from the perspective of file function ).
Program files
Include source files ( The suffix is .c), Target file (windows Environment suffix is .obj), Executable program (windows Environment suffix is .exe).
Data files
The content of the file is not necessarily a program , It's the data that the program reads and writes when it runs , For example, the file from which the program needs to read data , Or output content file .
What we discuss in this blog is Data files . In the previous chapters, the input and output of the processed data are targeted at the terminal , That is, input data from the keyboard of the terminal , The operation results are displayed on the display . In fact, sometimes we output information to disk , When necessary, read the data from the disk to the memory for use , What we are dealing with here is the files on the disk .
file name
A file should have a unique file ID , So that users can identify and reference .
The filename contains 3 part : File path + File name trunk + file extension
for example : c:\code\test.txt
For convenience , Document identification is often referred to as file name .
Opening and closing of files
The file pointer
Buffer file system , The key concept is “ File type pointer ”, abbreviation “ The file pointer ”.
Each used file has a corresponding file information area in memory , It is used to store information about files ( Such as file name
word , File status and current file location, etc ). This information is stored in a structure variable . The structure type is systematic
Declarative , The name FILE.
for example ,VS2013 The compiler environment provides stdio.h The header file has the following file type declaration :
struct _iobuf char * int char * int int int int char * }; typedef structDifferent C Compiler FI
Every time you open a file , The system will automatically create a FILE Structural variables , And fill in the information ,
Users don't have to care about details .
It's usually through a FILE To maintain this FILE Structural variables , This is more convenient to use
Now we can create a FILE* Pointer variable for :
FILE* pf;// File pointer variable
Definition pf It's a point FILE Pointer variable of type data . You can make pf Point to the file information area of a file ( It's a structural variable ). Through the information in the file information area, you can access the file . in other words , Through the file pointer variable, you can find the file associated with it .

Opening and closing of files
The file should be opened before reading and writing , The file should be closed after use .
In programming , While opening the file , Will return to one FILE* A pointer variable to the file , It is also equivalent to establishing the relationship between pointer and file .
ANSIC To prescribe the use of fopen Function to open a file ,fclose To close the file
// Open file
FILE * fopen (const char * filename, const char * mode)
// Close file
int fclose ( FILE * stream ); * filename, const char * mode );
Open mode :
| How files are used | meaning | If the specified file does not exist |
|---|---|---|
| “r”( read-only ) | To enter data , Open an existing text file | error |
| “w”( Just write ) | To output data , Open a text file | Create a new file |
| “a”( Additional ) | Add data to the end of the text file | Create a new file |
| “rb”( read-only ) | To enter data , Open a binary file | error |
| “wb”( Just write ) | To output data , Open a binary file | Create a new file |
| “ab”( Additional ) | Add data to the end of a binary file | error |
| “r+”( Reading and writing ) | For reading and writing , Open a text file | error |
| “w+”( Reading and writing ) | For reading and writing , Suggest a new file | Create a new file |
| “a+”( Reading and writing ) | Open a file , Read and write at the end of the file | Create a new file |
| “rb+”( Reading and writing ) | Open a binary file for reading and writing | error |
| “wb+”( Reading and writing ) | For reading and writing , Create a new binary file | Create a new file |
| “ab+”( Reading and writing ) | Open a binary file , Read and write at the end of the file | Create a new file |
about fopen and fclose Use :
#include <stdio.h>
#include <errno.h>
int main()
{
FILE* pf = fopen("test.txt", "r");
if (pf == NULL)
{
printf("%s\n", strerror(errno));
return 1;
}
// Reading documents
// Close file
fclose(pf);
pf = NULL;
return 0;
}

about No such file or directory, We can create it under the directory test.txt file ( Relative paths ) Solve this problem . If you want to open the file on the desktop , We open the absolute path ( In the position of the attribute )!!! Remember to add escape characters
#include <stdio.h>
#include <errno.h>
int main()
{
FILE* pf = fopen("C:\\Users\\ASUS\\Desktop\\test.txt", "r");
if (pf == NULL)
{
printf("%s\n", strerror(errno));
return 1;
}
// Reading documents
// Close file
fclose(pf);
pf = NULL;
return 0;
}
Sequential reading and writing of files
| function | Function name | Apply to |
|---|---|---|
| Character input function | fgetc | All input streams |
| Character output function | fputc | All output streams |
| Text line input function | fgets | All input streams |
| Text line output function | fputs | All output streams |
| Format input function | fscanf | All input streams |
| Format output function | fprintf | All output streams |
| Binary input | fread | file |
| Binary output | fwrite | file |
For so many functions , We have to practice through code :
Writing characters
int fputs ( const char * str, FILE * stream );
#include <stdio.h>
#include <errno.h>
int main()
{
FILE* pf = fopen("test.txt", "w");
if (pf == NULL)
{
printf("%s\n", strerror(errno));
return 1;
}
// Writing documents
fputc('a', pf);
// I'm not sure about the documents
fclose(pf);
pf = NULL;
return 0;
}
Find the path to view the file :
Read characters
int fgetc ( FILE * stream );
#include <stdio.h>
#include <errno.h>
int main()
{
FILE* pf = fopen("test.txt", "r");
if (pf == NULL)
{
printf("%s\n", strerror(errno));
return 1;
}
// Reading documents
int ch = fgetc(pf);
printf("%c\n", ch);
// I'm not sure about the documents
fclose(pf);
pf = NULL;
return 0;
}

The return type is int To accommodate special values EOF, This means failure . Based on this , We can loop out :
#include <stdio.h>
#include <errno.h>
int main()
{
FILE* pf = fopen("test.txt", "r");
if (pf == NULL)
{
printf("%s\n", strerror(errno));
return 1;
}
// Reading documents
int ch = 0;
while ((ch = fgetc(pf))!= EOF)
{
printf("%c ",ch);
}
// I'm not sure about the documents
fclose(pf);
pf = NULL;
return 0;
}

Write a line of data
int fputs ( const char * str, FILE * stream );
#include <stdio.h>
#include <errno.h>
// Write a line of data
int main()
{
FILE* pf = fopen("test.txt", "w");
if (pf == NULL)
{
printf("%s\n", strerror(errno));
return 1;
}
// Write a line of data
fputs("hello", pf);
fclose(pf);
pf = NULL;
return 0;
}
Open the current directory :
We found that the previous content was gone , about fputs for , Before the meeting . If you want to keep the previous content , We can use "a" Append to perform related operations :
#include <stdio.h>
#include <errno.h>
int main()
{
FILE* pf = fopen("test.txt", "a");
if (pf == NULL)
{
printf("%s\n", strerror(errno));
return 1;
}
// Write a line of data
fputs("hello", pf);
fclose(pf);
pf = NULL;
return 0;
}
Open again :
There is no newline for the data , We can add one by ourselves \n that will do
Read a row of data
char * fgets ( char * str, int num, FILE * stream );
#include <stdio.h>
#include <errno.h>
// Read a row of data
int main()
{
FILE* pf = fopen("test.txt", "r");
if (pf == NULL)
{
printf("%s\n", strerror(errno));
return 1;
}
// Read a row of data
char arr[20];
fgets(arr,5,pf);
printf("%s\n", arr);
fclose(pf);
pf = NULL;
return 0;
}

read 5 Data , What you really read is talent 4 individual , One more ’\0’!!!
Of course , For error reporting information strerror We can use perror To replace ( Here's to demonstrate the effect , I put test.txt File deleted )
#include <stdio.h>
#include <errno.h>
// Read a row of data
int main()
{
FILE* pf = fopen("test.txt", "r");
if (pf == NULL)
{
//printf("%s\n", strerror(errno));
perror("fopen");
return 1;
}
// Read a row of data
char arr[20];
fgets(arr,5,pf);
printf("%s\n", arr);
fclose(pf);
pf = NULL;
return 0;
}

Format output
int fprintf ( FILE * stream, const char * format, ... );
struct S
{
char arr[10];
int age;
float score;
};
int main()
{
struct S s = {
"zhangsan",25,50.5f };
FILE* pf = fopen("test.txt", "w");
if (pf == NULL)
{
perror("fopen");
}
fprintf(pf,"%s %d %f", s.arr, s.age, s.score);
fclose(pf);
pf = NULL;
return 0;
}
Open the file under the directory :
Format input
int fscanf ( FILE * stream, const char * format, ... );
struct S
{
char arr[10];
int age;
float score;
};
int main()
{
struct S s = {
0};
FILE* pf = fopen("test.txt", "r");
if (pf == NULL)
{
perror("fopen");
}
fscanf(pf, "%s %d %f", s.arr, &(s.age), &(s.score));
printf("%s %d %f\n",s.arr,s.age,s.score);
fclose(pf);
pf = NULL;
return 0;
}

Someone here will say , The use fprintf Print it on the screen ?
struct S
{
char arr[10];
int age;
float score;
};
int main()
{
struct S s = {
0};
FILE* pf = fopen("test.txt", "r");
if (pf == NULL)
{
perror("fopen");
}
fscanf(pf, "%s %d %f", s.arr, &(s.age), &(s.score));
fprintf(stdout,"%s %d %f\n",s.arr,s.age,s.score);
fclose(pf);
pf = NULL;
return 0;
}

thus , The functions we learned earlier are all text , What about binary
size_t fwrite ( const void * ptr, size_t size, size_t count, FILE * stream );
size_t fread ( void * ptr, size_t size, size_t count, FILE * stream );
struct S
{
char arr[10];
int age;
float score;
};
int main()
{
struct S s = {
"zhangsan",25,50.5f };
// Write to a file in binary form
FILE* pf = fopen("test.txt", "w");
if (pf == NULL)
{
perror("fopen");
return 1;
}
// Write in binary
fwrite(&s, sizeof(struct S), 1, pf);
fclose(pf);
pf = NULL;
}
Open the file under the directory :

struct S
{
char arr[10];
int age;
float score;
};
int main()
{
struct S s = {
0};
// Write to a file in binary form
FILE* pf = fopen("test.txt", "rb");
if (pf == NULL)
{
perror("fopen");
return 1;
}
// Read in binary
fread(&s, sizeof(struct S), 1, pf);
printf("%s %d %f", s.arr, s.age, s.score);
fclose(pf);
pf = NULL;
}

scanf: It is a formatted input statement for standard input
printf: It is a formatted output statement for standard output
fscanf: It is a formatted input statement for all input streams
fprintf: Is a formatted output statement for all output streams
sscanf: From a string into a formatted data
int sscanf ( const char * s, const char * format, ...);
sprintf: Write a formatted data into a string , The essence is to convert a formatted data into a string
int sprintf ( char * str, const char * format, ... );
struct S
{
char arr[10];
int age;
float score;
};
int main()
{
struct S s = {
"zhangsan",20,55.5f };
char buf[100] = {
0 };
sprintf(buf,"%s %d %f", s.arr, s.age, s.score);
printf("%s\n", buf);
return 0;
}

struct S
{
char arr[10];
int age;
float score;
};
int main()
{
struct S s = {
"zhangsan",20,55.5f };
struct S tmp = {
0 };
char buf[100] = {
0 };
sprintf(buf,"%s %d %f", s.arr, s.age, s.score);
printf("%s\n", buf);
// From a string buf Get a formatted data to tmp in
sscanf(buf,"%s %d %f", tmp.arr, &(tmp.age), &(tmp.score));
printf(" format :%s %d %f\n", tmp.arr, tmp.age, tmp.score);
return 0;
}

Random reading and writing of documents
The previous functions have a feature , That is, you can only read and write in order . Let's take a look at some functions that can be read and written randomly
fseek
Locate the file pointer according to its position and offset
int fseek ( FILE * stream, long int offset, int origin );
Let's take a look at our current test.txt What is the content of :
int main()
{
FILE* pf = fopen("test.txt", "r");
if (pf == NULL)
{
printf("%s\n", strerror(errno));
return 1;
}
// Reading documents
// Locate file pointer
fseek(pf,2,SEEK_SET);
int ch = fgetc(pf);
printf("%c\n", ch);
ch = fgetc(pf);
printf("%c\n", ch);
fclose(pf);
pf = NULL;
return 0;
}

int main()
{
FILE* pf = fopen("test.txt", "r");
if (pf == NULL)
{
printf("%s\n", strerror(errno));
return 1;
}
// Reading documents
// Locate file pointer
fseek(pf,2,SEEK_SET);
int ch = fgetc(pf);
printf("%c\n", ch);
fseek(pf, 2, SEEK_CUR);
ch = fgetc(pf);
printf("%c\n", ch);
fclose(pf);
pf = NULL;
return 0;
}

ftell
Returns the offset of the file pointer from its starting position
long int ftell ( FILE * stream );
int main()
{
FILE* pf = fopen("test.txt", "r");
if (pf == NULL)
{
printf("%s\n", strerror(errno));
return 1;
}
// Reading documents
// Locate file pointer
fseek(pf, 2, SEEK_SET);
int ch = fgetc(pf);
printf("%c\n", ch);
printf("%d\n", ftell(pf));//3
//fseek(pf, 2, SEEK_CUR);
fseek(pf, -1, SEEK_END);
ch = fgetc(pf);
printf("%c\n", ch);
printf("%d\n", ftell(pf));//6
fclose(pf);
pf = NULL;
return 0;
}

rewind
Return the file pointer to the beginning of the file
void rewind ( FILE * stream );
int main()
{
FILE* pf = fopen("test.txt", "r");
if (pf == NULL)
{
printf("%s\n", strerror(errno));
return 1;
}
// Reading documents
// Locate file pointer
fseek(pf, 2, SEEK_SET);
int ch = fgetc(pf);
printf("%c\n", ch);
printf("%d\n", ftell(pf));//3
//fseek(pf, 2, SEEK_CUR);
fseek(pf, -1, SEEK_END);
ch = fgetc(pf);
printf("%c\n", ch);
printf("%d\n", ftell(pf));//6
rewind(pf);
ch = fgetc(pf);
printf("%c\n", ch);//a
fclose(pf);
pf = NULL;
return 0;
}

Text files and binaries
According to the organization of data , Data files are called text file perhaps Binary .
If it's required to use ASCII In the form of code , You need to convert before storing . With ASCII The file stored in the form of characters is text file .
How is a data stored in memory ?
All characters are written in ASCII stored , Numerical data can be used either ASCII stored , It can also be stored in binary form .
If there are integers 10000, If the ASCII Code output to disk , The disk is occupied by 5 Bytes ( One byte per character ), and
Binary output , On the disk 4 Bytes

Test code :
#include <stdio.h>
int main()
{
int a = 10000;
FILE* pf = fopen("test.txt", "wb");
fwrite(&a, 4, 1, pf);// The binary form is written to the file
fclose(pf);
pf = NULL;
return 0;
}
I can't understand it when I open the file :
We can go through VS Open binary editor :

Determination of the end of file reading
Keep in mind : During file reading , Out-of-service feof The return value of the function is directly used to determine whether the end of the file
Instead, it applies when the file reading ends , The judgment is that the read failed and ended , Or end of file
** Whether the reading of text file is finished , Determine whether the return value is EOF ( fgetc ), perhaps NULL ( fgets )** for example :
fgetc Judge whether it is EOF .
fgets Determine whether the return value is NULL
Judgment of reading end of binary file , Judge whether the return value is less than the actual number to be read . for example :
fread Judge whether the return value is less than the actual number to be read .
below , Let's take an example :
Examples of text files :
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int c; // Be careful :int, Not char, Ask to deal with EOF
FILE* fp = fopen("test.txt", "r");
if(!fp) {
perror("File opening failed");
return EXIT_FAILURE;
}
//fgetc When reading fails or the end of the file is encountered , Will return to EOF
while ((c = fgetc(fp)) != EOF) // standard C I/O Read file cycle
{
putchar(c);
}
// Judge why it ended
if (ferror(fp))
puts("I/O error when reading");
else if (feof(fp))
puts("End of file reached successfully");
fclose(fp);
}
Examples of binary files :
#include <stdio.h>
enum {
SIZE = 5 };
int main(void)
{
double a[SIZE] = {
1.,2.,3.,4.,5.};
FILE *fp = fopen("test.bin", "wb"); // Binary mode must be used
fwrite(a, sizeof *a, SIZE, fp); // Write double Array of
fclose(fp);
double b[SIZE];
fp = fopen("test.bin","rb");
size_t ret_code = fread(b, sizeof *b, SIZE, fp); // read double Array of
if(ret_code == SIZE) {
puts("Array read successfully, contents: ");
for(int n = 0; n < SIZE; ++n) printf("%f ", b[n]);
putchar('\n');
} else {
// error handling
if (feof(fp))
printf("Error reading test.bin: unexpected end of file\n");
else if (ferror(fp)) {
perror("Error reading test.bin");
}
}
fclose(fp);
}
File buffer
ANSIC The standard is “ Buffer file system ” Processing of data files , The so-called buffer file system means that the system automatically opens up a block in memory for each file being used in the program “ File buffer ”. Data output from memory to disk is first sent to a buffer in memory , After the buffer is filled, it is sent to the disk together . If you read data from disk to computer , Then read the data from the disk file and input it into the memory buffer ( Fill the buffer ), And then send the data from the buffer to the program data area one by one ( Program variables, etc ). The size of the buffer depends on C The compiler system decides .

#include <stdio.h>
#include <windows.h>
int main()
{
FILE* pf = fopen("test.txt", "w");
fputs("abcdef", pf);// Put the code in the output buffer first
printf(" sleep 10 second - The data has been written , open test.txt file , Found no content in the file \n");
Sleep(10000);
printf(" Refresh buffer \n");
fflush(pf);// When the buffer is flushed , Write the data in the output buffer to a file ( disk )
// notes :fflush In high version VS It can't be used on
printf(" Sleep again 10 second - here , Open again test.txt file , There's something in the file \n");
Sleep(10000);
fclose(pf);
// notes :fclose When closing a file , It also flushes the buffer
pf = NULL;
return 0;
}


Because there is a buffer ,C Language when operating files , You need to flush the buffer or close the file at the end of the file operation
Pieces of . If you don't do , May cause problems in reading and writing files .
summary
That's all C Knowledge of language files . Let's start with the concept of documents , Go deeper , If it feels good , I'd like to support you , The support of the guys is the driving force of my creation
边栏推荐
- 手机开通中信证券账户安全吗?
- 力扣 565. 数组嵌套
- 总结阅读器与直播的奇怪交互:复习双迪技术
- The unique index exception of the dream database in the Xinchuang environment cannot intercept the duplicatekeyexception
- Ugui source code analysis - clipperregistry
- openresty ngx_ Lua shared memory
- MySQL - table index overview
- 模板的初识
- Ugui source code analysis - iclipper
- Does flush mobile phone software need money to open an account online for stock speculation? Is it safe to open an account?
猜你喜欢

CSGO突然返回桌面,并且其他应用无反应,如何不重启关闭

Pwnthebox, Web: Double - S

张朝阳夜跑33公里:直播聊物理 揭示“超级月亮”成因

Mysql如何实现不存在则插入,存在则更新

["code" power is fully open, and "chapter" shows strength] list of contributors to the task challenge in the first quarter of 2022

手写简易Promise代码注释

个人 IP 实验室周复盘 · 第 19 期

Opencv image transparent area clipping imagecroppingtrn

CH549/CH548学习笔记1 - 硬件设计

UGUI源码解析——RectMask2D
随机推荐
深度学习环境配置Pytorch
Summary of common problems of SolidWorks assembly (updated at any time)
同花顺软件线上开户免费吗?开户安全吗?
ArrayList source code analysis I
UGUI源码解析——IClipper
UGUI源码解析——RectMask2D
UGUI源码解析——ClipperRegistry
Latex basic grammar summary
MySQL 正則錶達式
MySQL - 表索引概述
Csgo suddenly returns to the desktop, and other applications are unresponsive. How can we not restart and close it
同花顺软件炒股线上怎么免费吗??开户安全吗?
基于深度学习的人脸识别闸机开发(基于飞桨PaddlePaddle)
CH549/CH548学习笔记2 - 系统时钟
["code" power is fully open, and "chapter" shows strength] list of contributors to the task challenge in the first quarter of 2022
PwnTheBox,Web:Double-S
Definition and usage of callback function and qsort function in C language
ROS与STM32通信的实现
Read the paper: temporary graph networks for deep learning on dynamic graphs
MySQL - 表字段的自增约束

