当前位置:网站首页>Preliminary introduction to C miscellaneous lecture document
Preliminary introduction to C miscellaneous lecture document
2022-07-06 09:59:00 【Bright-SKY】
Catalog
Knowledge point 1【 Overview of the document 】
1、 Classification of documents
2、 Classification of disk files
Knowledge point 2【 Library function of operation file 】
3、 Read and write one character at a time
(1)、 Byte read operation fgetc
(2)、 Byte write operation fputc
4、 Read and write one string at a time
(1)、 Use fgets Get string from file
(2)、 Use fputs Write a string to the file
5、 Reading and writing of file blocks fread fwrite Memory data as is Output to disk
1、 Use fwrite take Data blocks Write to a file
2、 Use fread From file Read Data blocks
Knowledge point 1【 Overview of the document 】
1、 Classification of documents
Disk files : Files are used to store programs 、 file 、 Audio 、 Video data 、 Pictures and other data .
Device file : In the operating system, every input connected to the host 、 The output device is treated as a file , Put their input 、 Output is equivalent to disk text Reading and writing of documents

( The purpose of the buffer is : Improve access efficiency Disk life )
2、 Classification of disk files
Physically All disk files are Binary storage , In bytes Sequential storage .
logically Document classification :
text file : File based on character encoding
Binary : File based on value encoding


summary :

3、 The file pointer


Be careful : Don't care about beginners FILE The details of the It only needs Will use FILE Just define pointer variables :FILE *fp=NULL;

Knowledge point 2【 Operation file's Library function 】
1、fopen Open file
#include <stdio.h>
FILE *fopen(const char *path, const char *mode);mode:
read-write permission :r read w Write a Additional + Can read but write t text file ( Omit ) b Binary
r: With read-only Way to open a file
file non-existent return NULL;
file There is return The file pointer , Perform subsequent read operations
w: With Just write Way to open a file
file does not exist , Create this file with the specified file name , And open the file ;
If document There is , Empty The contents of the document , Open file , And then write ;
If the file cannot be opened ( For example, the file is read-only ), return NULL
a: With Additional Way to open a file
file does not exist , Create this file with the specified file name ( Same as w)
If the file exists , From the file Ending Write operation


2、 Close file fclose
#include <stdio.h>
int fclose(FILE *fp);
3、 Read and write one character at a time
(1)、 Byte read operation fgetc
int fgetc(FILE *stream)// Read operations Return value :
With t The way : Read to the end of the file and return EOF
With b The way : Read to the end of the file , Use feof( The back can speak )

void test03()
{
char buf[128]="";
int i=0;
FILE *fp = NULL;
//1、 Use fopen Open a file Get file pointer
fp = fopen("a.txt", "r");
if(fp == NULL)
{
perror("fopen");
return;
}
//2、 Operations on files fgetc
while(1)
{
//fgetc Call once Read a byte
buf[i] = fgetc(fp);
if(buf[i] == EOF)//EOF The table has been aligned to the end of the file
{
break;
}
i++;
}
printf("buf=%s\n", buf);
//3、 Close file
fclose(fp);
}Running results : In advance, Local establish a.txt The contents of the document by hello file

(2)、 Byte write operation fputc
int fputc(int c, FILE *stream)// Write operations
fputc take c The value of is written as streamReturn value :
If the output is successful , Returns the byte value of the output ;
If the output fails , Returns a EOF
EOF Is in stdio.h Symbols defined in the document

void test04()
{
char buf[128]="";
int i=0;
FILE * fp =NULL;
fp = fopen("b.txt", "w");
if(fp == NULL)
{
perror("fopen");
return;
}
// Use fputc Write the data of the file
printf(" Please enter the string to write to the file :");
fgets(buf,sizeof(buf),stdin);// Will get line breaks
buf[strlen(buf)-1] = 0;// Remove the newline character of keyboard input
// The string buf The elements in Write to the file one by one
while(buf[i] != '\0')
{
fputc(buf[i], fp);
i++;
}
fclose(fp);
}Running results :

routine : From a file ( text file ) Read all information in , Write to another file
void test05()
{
// demand : from a.txt Read file contents Write to b.txt
FILE *fp1 =NULL;
FILE *fp2 =NULL;
// Open as read-only a.txt
fp1 = fopen("a.txt","r");
if(fp1 == NULL)
{
perror("fopen");
return;
}
// Open in write only mode b.txt
fp2 = fopen("b.txt","w");
if(fp2 == NULL)
{
perror("fopen");
return;
}
// from fp1 in Every read byte Write to fp2 in
while(1)
{
char ch;
// read
ch = fgetc(fp1);
if(ch == EOF)// Read to the end of the file
break;
// Write
fputc(ch,fp2);
}
fclose(fp1);
fclose(fp2);
return;
}4、 Read and write one string at a time
(1)、 Use fgets Get string from file
char *fgets(char *s, int size, FILE *stream)from stream Read characters from the file referred to , Stop reading when you encounter a newline character or the end of the file .
Or read size-1 Stop reading bytes , After the read content, a \0, As the end of a string
Return value :
success : Return the address of the first element of the read string
Failure : return NULL

Get the data of one line of the file :
void test07()
{
char buf[128]="";
FILE *fp = NULL;
char *path = "c.txt";
fp = fopen(path, "r");
if(fp == NULL)
{
perror("fopen");
return;
}
//err Open a file named "path" instead of path The file name that points to "c.txt"
//fp = fopen("path", "r");
//fp = fopen("c.txt", "r");
while(fgets(buf,sizeof(buf),fp))
{
printf("%s\n", buf);
}
fclose(fp);
}Running results :

(2)、 Use fputs Write a string to the file
int fputs(const char *s, FILE *stream); 
Case study :
void test06()
{
// Pointer array
char *buf[]={" The bright moon in front of the window \n"," Suspected frost on the ground \n"," look at the bright moon \n"," Bow your head and think of your hometown "};
int n = sizeof(buf)/sizeof(buf[0]);
FILE *fp = NULL;
int i=0;
fp = fopen("c.txt", "w");
if(fp == NULL)
{
perror("fopen");
return;
}
for(i=0;i<n; i++)
{
fputs(buf[i], fp);
}
fclose(fp);
}Running results :

5、 Reading and writing of file blocks fread fwrite Memory data as is Output to disk
1、 Use fwrite take Data blocks Write to a file

typedef struct
{
char name[16];// full name
int deff;// defense
int atk;// attack
}HERO;
void test08()
{
HERO hero[]={
{" De Marcia ",80, 60},
{" Blind monk ",90, 80},
{" Small method ",40, 85},
{" Tristana ",50, 90}
};
int n = sizeof(hero)/sizeof(hero[0]);
FILE *fp = NULL;
fp = fopen("hero.txt", "w");
if(fp == NULL)
{
perror("fopen");
return;
}
//fwrite Put the data in memory as it is Output to In file
// Data written to a file Inconvenient User view however Does not affect the Program reading
fwrite(hero, sizeof(HERO), n, fp);
fclose(fp);
}Running results :

2、 Use fread From file Read Data blocks

The whole block number is returned Less than one piece It doesn't count

Case study :
void test09()
{
HERO hero[4];
int i=0;
FILE *fp = NULL;
fp = fopen("hero.txt", "r");
if(fp == NULL)
{
perror("fopen");
return;
}
fread(hero,sizeof(HERO), 4, fp);
for(i=0;i<4;i++)
{
//printf(" Hero name :《%s》, defense :《%d》, damage :《%d》\n", \
hero[i].name,hero[i].deff,hero[i].atk);
printf(" Hero name :《%s》, defense :《%d》, damage :《%d》\n", \
(hero+i)->name,(hero+i)->deff,(hero+i)->atk);
}
fclose(fp);
}Running results :

边栏推荐
- 大学想要选择学习自动化专业,可以看什么书去提前了解?
- Installation of pagoda and deployment of flask project
- MapReduce instance (IX): reduce end join
- A new understanding of RMAN retention policy recovery window
- MySQL ERROR 1040: Too many connections
- Configure system environment variables through bat script
- Automation sequences of canoe simulation functions
- Cap theory
- 听哥一句劝,按这套嵌入式的课程内容和课程体系去学习
- 西南大学:胡航-关于学习行为和学习效果分析
猜你喜欢

寶塔的安裝和flask項目部署

嵌入式开发中的防御性C语言编程

C杂讲 双向循环链表
![[CV] target detection: derivation of common terms and map evaluation indicators](/img/e8/04cc8336223c0ab2dea5638def88df.jpg)
[CV] target detection: derivation of common terms and map evaluation indicators
![17 medical registration system_ [wechat Payment]](/img/b4/f9abfa0fb0447d727078069d888b57.png)
17 medical registration system_ [wechat Payment]

Hero League rotation map automatic rotation

Take you back to spark ecosystem!

Embedded development is much more difficult than MCU? Talk about SCM and embedded development and design experience

The programming ranking list came out in February. Is the result as you expected?
![《ASP.NET Core 6框架揭秘》样章发布[200页/5章]](/img/4f/5688c391dd19129d912a3557732047.jpg)
《ASP.NET Core 6框架揭秘》样章发布[200页/5章]
随机推荐
在CANoe中通过Panel面板控制Test Module 运行(高级)
The programming ranking list came out in February. Is the result as you expected?
在CANoe中通过Panel面板控制Test Module 运行(初级)
The 32-year-old fitness coach turned to a programmer and got an offer of 760000 a year. The experience of this older coder caused heated discussion
西南大学:胡航-关于学习行为和学习效果分析
CANoe不能自动识别串口号?那就封装个DLL让它必须行
vscode 常用的指令
Upload vulnerability
oracle sys_ Context() function
May brush question 01 - array
CANoe CAPL文件操作目录合集
Single chip microcomputer realizes modular programming: Thinking + example + system tutorial (the degree of practicality is appalling)
一大波開源小抄來襲
Take you back to spark ecosystem!
华南技术栈CNN+Bilstm+Attention
Flash operation and maintenance script (running for a long time)
jar运行报错no main manifest attribute
AI的路线和资源
Elk project monitoring platform deployment + deployment of detailed use (II)
How does the single chip microcomputer execute the main function from power on reset?