当前位置:网站首页>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 :

边栏推荐
- 机械工程师和电气工程师方向哪个前景比较好?
- CANoe下载地址以及CAN Demo 16的下载与激活,并附录所有CANoe软件版本
- 宝塔的安装和flask项目部署
- cmooc互联网+教育
- 018. Valid palindromes
- Constants and pointers
- MapReduce instance (x): chainmapreduce
- AI的路线和资源
- 嵌入式中的合作开发--函数指针
- CAPL script printing functions write, writeex, writelineex, writetolog, writetologex, writedbglevel do you really know which one to use under what circumstances?
猜你喜欢

History of object recognition

Embedded development is much more difficult than MCU? Talk about SCM and embedded development and design experience
![[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

Some thoughts on the study of 51 single chip microcomputer

Release of the sample chapter of "uncover the secrets of asp.net core 6 framework" [200 pages /5 chapters]
![[NLP] bert4vec: a sentence vector generation tool based on pre training](/img/fd/8e5e1577b4a6ccc06e29350a1113ed.jpg)
[NLP] bert4vec: a sentence vector generation tool based on pre training

max-flow min-cut

Installation of pagoda and deployment of flask project

17 医疗挂号系统_【微信支付】

docker MySQL解决时区问题
随机推荐
C杂讲 文件 初讲
Flash operation and maintenance script (running for a long time)
Function description of shell command parser
[deep learning] semantic segmentation: thesis reading (neurips 2021) maskformer: per pixel classification is not all you need
华南技术栈CNN+Bilstm+Attention
Solve the problem of too many small files
硬件工程师的真实前途我说出来可能你们不信
MapReduce instance (IX): reduce end join
Vh6501 Learning Series
CANoe不能自动识别串口号?那就封装个DLL让它必须行
The replay block of canoe still needs to be combined with CAPL script to make it clear
Competition vscode Configuration Guide
C杂讲 动态链表操作 再讲
May brush question 01 - array
[one click] it only takes 30s to build a blog with one click - QT graphical tool
I2C summary (single host and multi host)
How can I take a shortcut to learn C language in college
History of object recognition
PR 2021 quick start tutorial, first understanding the Premiere Pro working interface
Embedded development is much more difficult than MCU? Talk about SCM and embedded development and design experience