当前位置:网站首页>[C language] file operation
[C language] file operation
2022-07-23 09:11:00 【SouLinya】
List of articles
1. Why use files ?
for instance , For example, we are writing our address book , Student management system , Parking lot management system , When the program runs , We can increase 、 The function of deleting data , At this time, the data is stored in memory , When the program exits , The data in the program naturally does not exist , The developed memory is also returned to the operating system , The next time you run the address book program , The data has to be re entered , It's complicated .
And the role of documents is : When using files, we can write data into a file , Directly stored on the hard disk of the computer , Read the data in the file directly when you want to use it next time , You can get the data written before , Data persistence is achieved .
2. What is a document ?
A file on disk is a file .
Generally in programming , We divide documents into two kinds : Program files and data files .
2.1 Program files
Include source files ( The suffix is .c), Target file (windows Environment suffix is .obj), Executable program (windows Environmental Science
The suffix is .exe).
2.2 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 .
2.3 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
c:\code\ Is the location of the file , Also known as file path
test Is the file name trunk
.txt It's a file suffix
2.4 File operation steps
1. Open file
2. read / Writing documents
3. Close file
3. Opening and closing of files
3.1 The file pointer
Buffer file system , The key concept is “ File type pointer ”, abbreviation “ The file pointer ”.
Each used file will open a corresponding File information area , It is used to store information about files ( Such as the name of the document , File status , File location, etc ). This information is stored in a structure variable . The structure type is system declared , be known as FILE
stay VS2013 in , There are the following Document type declaration
struct _iobuf {
char *_ptr;
int _cnt;
char *_base;
int _flag;
int _file;
int _charbuf;
int _bufsiz;
char *_tmpfname;
};
typedef struct _iobuf FILE;
Every time you open a file , The system will automatically create a FILE Structure variables of structure type , And fill in the information . We usually pass FILE The pointer maintains this FILE Structural variables . File pointer variable :FILE* pf.
pf Point to the file information area of a file ( Structural variable ), The file can be accessed through the information in the file information area . in other words , Through the file pointer variable, you can find the file associated with it .
3.2 Open mode

3.3 Sequential reading and writing of files

3.4 Read and write characters
fputc
int fputc( int c, FILE *stream );
#include<stdio.h>
#include<string.h>
#include<errno.h>
int main()
{
FILE* pf = fopen("test.txt", "w");// Open the file as written
if (pf == NULL)
{
printf("%s\n",strerror(errno));//No such file or directory
return 1;
}
// Writing documents
char i = 'a';
for (i = 'a'; i <= 'z'; i++)
{
fputc(i, pf);// Character output function
}
fclose(pf);
pf = NULL;
return 0;
}
result :
fgetc
int fgetc( FILE *stream );
#include<stdio.h>
#include<string.h>
#include<errno.h>
int main()
{
FILE* pf = fopen("test.txt", "r");
if (pf == NULL)
{
printf("%s\n", strerror(errno));
return 1;
}
int ch;
while ((ch = fgetc(pf)) != EOF)
{
printf("%c", ch);
}
fclose(pf);
pf = NULL;
return 0;
}
3.5 Read and write a line of data
Note that in the next write , Previously written data will be destroyed , Don't want the previous data to be destroyed , You can choose "a" Append function
fputs- Write string
#include<stdio.h>
#include<string.h>
#include<errno.h>
int main()
{
FILE* pf = fopen("test.txt", "w");
if (pf == NULL)
{
printf("%s\n", strerror(errno));
}
fputs("hello world", pf);
// read : You need to create a new array
char arr[100] = {
0 };
fgets(arr, 6, pf);
printf("%s\n", arr);//hello
fclose(pf);
pf = NULL;
return 0;
}

3.6 Read and write text data
fprintf- Text writes data
fscanf- Text read data
#include<stdio.h>
#include<string.h>
#include<errno.h>
struct a
{
char name[20];
int age;
float score;
};
int main()
{
struct a s = {
"zhangsan","10",50.5f };
FILE* pf = fopen("test.txt", "w");
if (pf == NULL)
{
perror(pf);
return 1;
}
// Write text data
fprintf(pf, "%s %d %f", s.name, s.age, s.score);
fclose(pf);
pf = NULL;
return 0;
}
3.7 Binary read-write
size_t fwrite( const void *buffer, size_t size, size_t count, FILE *stream );
// Binary read-write
#include<stdio.h>
#include<string.h>
#include<errno.h>
struct a
{
char name[20];
int age;
float score;
};
int main()
{
//struct a s = { "zhangsan","10",50.5f };
struct a s = {
0 };
FILE* pf = fopen("test.txt", "rb");
//FILE* pf = fopen("test.txt", "wb");
if (pf == NULL)
{
perror(pf);
return 1;
}
// Binary write
//size_t fwrite( const void *buffer, size_t size, size_t count, FILE *stream );
//fwrite(&s, sizeof(struct a), 1, pf);
fread(&s, sizeof(struct a), 1, pf);
printf("%s %d %f", s.name, s.age, s.score);
fclose(pf);
pf = NULL;
return 0;
}
4. File stream
Any one of them C Language program , As long as it runs, it will open by default 3 A flow :
FILE* stdin- Standard input stream ( keyboard )
FILE* stdout- Standard output stream ( The screen )
FILE* strerr- Standard error flow ( The screen )
such as :fprintf(stdout,“%d”,12);
5. other
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
sprintf Convert a formatted data into a string
sscanf Convert a format into formatted data
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 };
// hold s The formatted data in is converted into a string and placed in buf in
sprintf(buf, "%s %d %f", s.arr, s.age, s.score);
//"zhangsan 20 55.500000";
printf(" character string :%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;
}
6. Text files and binaries
According to the organization of data , Data files are called Text file or binary file .
Data is stored in memory in binary form , If the output without conversion is to external memory , Binary files .
If it's required to use ASCII In the form of code , You need to convert before storing . With ASCII A file stored in the form of characters is a text file .
#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;
}
Binary values 
ASCII Code form 
7. Determination of the end of file reading
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 .
8. 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 memory
Impact area ( 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 .
边栏推荐
- Template school jumpserver security operation and maintenance audit screen
- Is it safe to open an account online? How about Galaxy Securities
- -bash: wget: 未找到命令
- 解读机器人视觉类别及应用原理
- 提升从改变开始...
- 启牛开户安全性高吗?说万3的佣金靠谱吗?
- JMeter --- JMeter installation tutorial
- NodeJS 基于 Dapr 构建云原生微服务应用,从 0 到 1 快速上手指南
- Summary of some open source libraries that drive MCU hardware debugger (including stlink debugger)
- 工作中遇到一个bug的解决过程
猜你喜欢

DOM series prohibit selected text and prohibit right-click menu

BGP experiment

There was an accident caused by MySQL misoperation, and "high availability" couldn't stand it

Internet download manager is simply a killer of downloaders

【并发编程】第二章:从核心源码深入ReentrantLock锁

数学建模——插值拟合

Unity3D学习笔记9——加载纹理

IDEA导出jar包到JMeter

Swin-Transformer-Object-Detection项目安装教程

【Try to Hack】AWVS安装和简单使用
随机推荐
华为应用已经调用了checkAppUpdate接口,为什么应用内不提示版本更新
openresty lua-resty-balancer动态负载均衡
Internet download manager is simply a killer of downloaders
OSI七层模型有哪七层?每一层分别有啥作用,这篇文章讲的明明白白!
How many of the 50 classic computer network interview questions can you answer? (II)
How many of the 50 classic computer network interview questions can you answer? (III)
UGUI源码解析——Mask
There was an accident caused by MySQL misoperation, and "high availability" couldn't stand it
Flutter 3.0
Canal realizes MySQL data synchronization
Print prime numbers between 100 and 200
NodeJS 基于 Dapr 构建云原生微服务应用,从 0 到 1 快速上手指南
【云原生】风云暗涌的时代,DBA们的利刃出鞘了
Kali 2022.2 installation
ADB 命令结合 monkey 的简单使用,超详细
2302. 统计得分小于 K 的子数组数目-滑动数组-双百代码
Is it safe to open an account online? How about Galaxy Securities
[try to hack] awvs installation and simple use
正则表达式转换为相应的文字小工具
跨境电商旺季来临,汇付国际收款0费率助你赢战旺季!