当前位置:网站首页>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 stream
Return 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 :
边栏推荐
- [one click] it only takes 30s to build a blog with one click - QT graphical tool
- 竞赛vscode配置指南
- Tianmu MVC audit II
- Defensive C language programming in embedded development
- 17 medical registration system_ [wechat Payment]
- 为什么大学单片机课上51+汇编,为什么不直接来STM32
- max-flow min-cut
- Docker MySQL solves time zone problems
- Installation de la pagode et déploiement du projet flask
- 美疾控中心:美国李斯特菌疫情暴发与冰激凌产品有关
猜你喜欢
MapReduce instance (x): chainmapreduce
I2C summary (single host and multi host)
[flask] crud addition and query operation of data
docker MySQL解决时区问题
C杂讲 文件 续讲
大学C语言入门到底怎么学才可以走捷径
Solve the problem of too many small files
[deep learning] semantic segmentation: thesis reading (neurips 2021) maskformer: per pixel classification is not all you need
在CANoe中通过Panel面板控制Test Module 运行(高级)
112 pages of mathematical knowledge sorting! Machine learning - a review of fundamentals of mathematics pptx
随机推荐
15 医疗挂号系统_【预约挂号】
嵌入式中的合作开发--函数指针
Hero League rotation chart manual rotation
Summary of May training - from a Guang
There are software load balancing and hardware load balancing. Which one to choose?
Keep these four requirements in mind when learning single chip microcomputer with zero foundation and avoid detours
MapReduce instance (x): chainmapreduce
17 medical registration system_ [wechat Payment]
Target detection -- yolov2 paper intensive reading
Selection of software load balancing and hardware load balancing
美疾控中心:美国李斯特菌疫情暴发与冰激凌产品有关
Sichuan cloud education and double teacher model
51单片机进修的一些感悟
A new understanding of RMAN retention policy recovery window
Tianmu MVC audit II
flask运维脚本(长时间运行)
在CANoe中通过Panel面板控制Test Module 运行(初级)
Mexican SQL manual injection vulnerability test (mongodb database) problem solution
Redis distributed lock implementation redison 15 questions
C杂讲 文件 续讲