当前位置:网站首页>C miscellaneous lecture continued
C miscellaneous lecture continued
2022-07-06 09:59:00 【Bright-SKY】
Catalog
Knowledge point 1【 Format read and write of file block 】( important )
1、fprintf Write operation of file
2、fscanf format Read operations
Knowledge point 2【 Random reading and writing of documents 】( important )
1、rewind Reset the file stream pointer
3、fseek Position pointer ( Reading and writing position )
4、feof() function Determine whether the file reaches the end of the file
Knowledge point 3【 File Encryptor 】
Knowledge point 1【 Format read and write of file block 】( important )
fprintf( Write ) fscanf( read )
1、fprintf Write operation of file
void test06()
{
HERO hero_buf[]={
{" De Marcia ", 80, 60}, {" Tristana ", 40, 80}, {" Small method ",50, 90}};
FILE *fp = NULL;
fp = fopen("hero.txt", "w");
if(fp == NULL)
{
perror("fopen");
return;
}
int i=0;
for ( i = 0; i < 3; i++)
{
fprintf(fp," full name :%s defense :%d attack :%d\n", \
hero_buf[i].name,hero_buf[i].def,hero_buf[i].atk);
}
fclose(fp);
}
2、fscanf format Read operations
void test07()
{
HERO hero_buf[3];
memset(hero_buf, 0, sizeof(hero_buf));
FILE *fp = NULL;
fp = fopen("hero.txt", "r");
if(fp == NULL)
{
perror("fopen");
return;
}
int i=0;
for ( i = 0; i < 3; i++)
{
fscanf(fp," full name :%s defense :%d attack :%d\n", \
hero_buf[i].name, &hero_buf[i].def,&hero_buf[i].atk);
}
for ( i = 0; i < 3; i++)
{
printf("%s %d %d\n", hero_buf[i].name, hero_buf[i].def,hero_buf[i].atk);
}
fclose(fp);
}
summary :
Byte operation :fgetc fputc
String manipulation :fgets fputs
Block operation :fread fwrite
Format operation :fscanf fprintf

Knowledge point 2【 Random reading and writing of documents 】( important )
File default Sequential reading and writing
Introduction of knowledge points :
void test01()
{
FILE *fp = NULL;
fp = fopen("c.txt", "w+");
if(fp == NULL)
{
perror("fopen");
return;
}
fputs("hello world", fp);
fclose(fp);
fp = fopen("c.txt", "r");
char buf[1024]="";
fgets(buf, sizeof(buf), fp);
printf("buf=%s\n",buf);
fclose(fp);
}
Resolve the above documents : When the papers are finished Need to be closed file Then reopen the file Let the file stream pointer Point to the beginning of the file Let's change Next file read operation
Random reading and writing of documents : Move the stream pointer of the file
rewind ftell fseek
1、rewind Reset the file stream pointer
void rewind(FILE *stream)
void test01()
{
FILE *fp = NULL;
fp = fopen("c.txt", "w+");
if(fp == NULL)
{
perror("fopen");
return;
}
fputs("hello world", fp);
// Reset the file stream pointer
rewind(fp);
char buf[1024]="";
fgets(buf, sizeof(buf), fp);
printf("buf=%s\n",buf);
fclose(fp);
}
2、ftell Measure the number of bytes from the file reading and writing position to the beginning of the file
long ftell(FILE *stream);
3、fseek Position pointer ( Reading and writing position )
int fseek(FILE *stream, long offset, int whence)
Case study 1: Pointer the file stream Navigate to the end of the file
fseek(fp, 0, 2);Case study 2: File data Read to memory at one time
#include <stdlib.h>
#include <string.h>
void test02()
{
FILE *fp = NULL;
fp = fopen("a.txt", "r");
if(fp == NULL)
{
perror("fopen");
return;
}
// Get the total file size
fseek(fp, 0, 2);// Pointer the file stream Navigate to the end of the file
long len = ftell(fp);// Get file size
rewind(fp);// Reset the file stream pointer ( Facilitate subsequent reading of file data )
printf("len = %ld\n", len);
// Apply for space according to the total size of the file
unsigned char *data = NULL;
data = (unsigned char *)calloc(1, len+1);
fread(data, len, 1, fp);
printf("%s\n", data);
free(data);
fclose(fp);
}
4、feof() function Determine whether the file reaches the end of the file
EOF macro It can only be used for Wen Wen Wen file
feof function It can be used for Text document Binary
void test07()
{
FILE *fp = NULL;
fp = fopen("a.txt","r");
if(fp == NULL)
{
perror("fopen");
return;
}
//feof(fp) Determine whether the file is end 0: not finished Not 0: End of the said
//while( feof(fp) == 0)// File not closed Only then circulates
while( !feof(fp) )
{
char ch = fgetc(fp);
printf("%c", ch);
}
fclose(fp);
}Running results :

Knowledge point 3【 File Encryptor 】
1、 Principle analysis
The encryption process :

The decryption process :

main.c
#include<stdio.h>
#include"fun.h"
int main(int argc,char *argv[])
{
while(1)
{
int cmd = 0;
print_help();
scanf("%d", &cmd);
if(cmd == 1)
{
char src_file[31]="";
char dst_file[31]="";
char *file_data = NULL;
unsigned long file_length = 0;
unsigned int passwd = 0;
//1、 Get source file Destination file name ( Reference resources API Realization )
get_file_name(dst_file, src_file);
//2、 Get the source file name Corresponding file Content ( Reference resources API Realization )
//char * read_src_file(unsigned long *file_length,char *src_file_name)
file_data = read_src_file(&file_length, src_file);
//3、 Get the password entered by the user ( Custom implementation )
printf(" Please enter your password :");
scanf("%u", &passwd);
//4、 Encrypt the contents of the file ( Reference resources API Realization )
file_data = file_text_encrypt(file_data,file_length,passwd);
//char * file_text_encrypt(char * src_file_text,unsigned long int length,unsigned int password)
//5、 Yes, encrypted The contents of the document Save to Destination file name
save_file(file_data, file_length,dst_file);
//void save_file(char* text,unsigned long int length,char * file_name)
}
else if(cmd == 2)
{
char src_file[31]="";
char dst_file[31]="";
char *file_data = NULL;
unsigned long file_length = 0;
unsigned int passwd = 0;
//1、 Get source file Destination file name ( Reference resources API Realization )
get_file_name(dst_file, src_file);
//void get_file_name(char * dest_file_name,char * src_file_name)
//2、 Get the source file name Corresponding file Content ( Reference resources API Realization )
file_data = read_src_file(&file_length, src_file);
//char * read_src_file(unsigned long int *file_length,char *src_file_name)
//3、 Get the password entered by the user ( Custom implementation )
printf(" Please enter your password :");
scanf("%u", &passwd);
//4、 Decrypt file contents ( Reference resources API Realization )
file_data = file_text_decrypt(file_data, file_length,passwd);
//char * file_text_decrypt(char * src_file_text,unsigned long int length,unsigned int password)
//5、 Yes, encrypted The contents of the document Save to Destination file name
save_file(file_data, file_length,dst_file);
//void save_file(char* text,unsigned long int length,char * file_name)
}
else if(cmd == 3)
{
break;
}
else
{
printf(" Please enter a correct option \n");
}
}
return 0;
}fun.c
#include<stdio.h>
#include<stdlib.h>
void print_help(void)
{
printf("**********1: Encrypt file **************\n");
printf("**********2: Decrypt files **************\n");
printf("**********3: Exit procedure **************\n");
}
void get_file_name(char * dest_file_name,char * src_file_name)
{
printf(" Please enter the name of your source file (30 Characters ):");
scanf("%s", src_file_name);
printf(" Please enter the name of your destination file (30 Characters ):");
scanf("%s", dest_file_name);
return;
}
char * read_src_file(unsigned long *file_length,char *src_file_name)
{
char *data = NULL;
FILE *fp = NULL;
fp = fopen(src_file_name,"r");
if(fp == NULL)
{
perror("fopen");
return NULL;
}
// Get the total length of the file
// Pointer the file stream location To the file The tail
fseek(fp,0,2);
// Get file length
*file_length = ftell(fp);
// Reset the file stream pointer
rewind(fp);
// according to The length of the file apply Heap space
data = (char *)calloc(1,*file_length);
if(data == NULL)
{
perror("calloc");
return NULL;
}
// Disposable Read file contents
fread(data, *file_length,1,fp);
fclose(fp);
// Put the first address of the space return
return data;
}
char * file_text_encrypt(char * src_file_text,unsigned long int length,unsigned int password)
{
int i=0;
for(i=0;i<length;i++)
{
src_file_text[i] += password;// Encryption process
}
return src_file_text;
}
void save_file(char* text,unsigned long int length,char * file_name)
{
FILE *fp = NULL;
fp = fopen(file_name, "w");
if(fp == NULL)
{
perror("fopen");
return;
}
// take data The data is saved to In file
fwrite(text, length, 1, fp);
fclose(fp);
// Release text Point to heap space
if(text != NULL)
{
free(text);
text =NULL;
}
printf(" Saved successfully !\n");
return;
}
char * file_text_decrypt(char * src_file_text,unsigned long int length,unsigned int password)
{
int i=0;
for(i=0;i<length;i++)
{
src_file_text[i] -= password;// Decryption process
}
return src_file_text;
}fun.h
#ifndef __FUN_H__
#define __FUN_H__
extern void print_help(void);
extern void get_file_name(char * dest_file_name,char * src_file_name);
extern char * read_src_file(unsigned long *file_length,char *src_file_name);
extern char * file_text_encrypt(char * src_file_text,unsigned long int length,unsigned int password);
extern void save_file(char* text,unsigned long int length,char * file_name);
#endifProject tips :
1: Open the file in binary mode for reading and writing .
2: Method of measuring file size :
1) use fseek() Locate the stream pointer to the end of the file .
2) use ftell() The function measures the position of the stream pointer, that is, the size of the file .
3: Read the contents of the document :
1) According to the size of the file, use malloc Apply for memory space to save the read content
2) When reading file data, read from the beginning of the file (rewind()).
Detailed design API Design reference :
1) Get the names of source and destination files from the keyboard
/**************************************************************************/
// The functionality : obtain Name of destination file and source file
// Parameters : src_file_name: Source file name character array first address .
// dest_file_name: The first address of the name character array of the destination file
/**************************************************************************/
void get_file_name(char * dest_file_name,char * src_file_name)
2) Read from the file
/**************************************************************************/
// The functionality : Read file contents
// Parameters :file_length: Integer pointer , The number of bytes saved in this address .
// src_file_name: File name , Read from this file .
// Return value : Read the first address of the string
// Measure the size of the file in this function , and malloc Space , Then read out the contents of the file and return , Read the first address of the character array
/**************************************************************************/
char * read_src_file(unsigned long int *file_length,char *src_file_name)
3) Character array encryption
/**************************************************************************/
// The functionality : Encrypted string
// Parameters :
// src_file_text: The string to encrypt . length: Length of string
// password: Encrypted password
// Return value : The first address of the encrypted string
// Encryption principle add password
/**************************************************************************/
char * file_text_encrypt(char * src_file_text,unsigned long int length,unsigned int password)
4) Decrypt string
/**************************************************************************/
// The functionality : Decrypt string
// Parameters :
// src_file_text: String to decrypt . length: Length of string
// password: Decrypt password
// Return value : The first address of the decrypted string
// thought ; Subtract each element in the array password Assign values to yourself .
/**************************************************************************/
char * file_text_decrypt(char * src_file_text,unsigned long int length,unsigned int password)
5) Save the file
/**************************************************************************/
// The functionality : Save the string to the destination file
// Parameters :
// text: The first address of the string to be saved
// file_name : Name of the destination file
// length: Length of string
// thought : Pass in the first address of the character array, the size of the array and the name of the saved file , You can save the array to a file
/**************************************************************************/
void save_file(char* text,unsigned long int length,char * file_name)
6) Print file information
/**************************************************************************/
//
// The functionality : Print help
//
//
/**************************************************************************/
void print_help()
{
printf("********1: Encrypt file ***********\n");
printf("********2: Decrypt files ***********\n");
printf("********3: Exit procedure ***********\n");
}
边栏推荐
- 西南大学:胡航-关于学习行为和学习效果分析
- CAPL script pair High level operation of INI configuration file
- 51单片机进修的一些感悟
- Contrôle de l'exécution du module d'essai par panneau dans Canoe (primaire)
- Solve the problem of too many small files
- Pointer learning
- Some thoughts on the study of 51 single chip microcomputer
- Target detection -- yolov2 paper intensive reading
- Routes and resources of AI
- May brush question 01 - array
猜你喜欢

CANoe下载地址以及CAN Demo 16的下载与激活,并附录所有CANoe软件版本

CANoe的数据回放(Replay Block),还是要结合CAPL脚本才能说的明白

What are the models of data modeling
![17 medical registration system_ [wechat Payment]](/img/b4/f9abfa0fb0447d727078069d888b57.png)
17 medical registration system_ [wechat Payment]

C杂讲 文件 续讲

Programmation défensive en langage C dans le développement intégré

CANoe不能自动识别串口号?那就封装个DLL让它必须行

Carolyn Rosé博士的社交互通演讲记录

The 32 year old programmer left and was admitted by pinduoduo and foreign enterprises. After drying out his annual salary, he sighed: it's hard to choose

Single chip microcomputer realizes modular programming: Thinking + example + system tutorial (the degree of practicality is appalling)
随机推荐
MapReduce instance (x): chainmapreduce
Tianmu MVC audit I
Download address of canoe, download and activation of can demo 16, and appendix of all canoe software versions
Some thoughts on the study of 51 single chip microcomputer
CAPL 脚本打印函数 write ,writeEx ,writeLineEx ,writeToLog ,writeToLogEx ,writeDbgLevel 你真的分的清楚什么情况下用哪个吗?
通过bat脚本配置系统环境变量
Contrôle de l'exécution du module d'essai par panneau dans Canoe (primaire)
Control the operation of the test module through the panel in canoe (primary)
Cmooc Internet + education
Combined search /dfs solution - leetcode daily question - number of 1020 enclaves
C杂讲 浅拷贝 与 深拷贝
17 医疗挂号系统_【微信支付】
Some thoughts on the study of 51 single chip microcomputer
单片机如何从上电复位执行到main函数?
AI的路线和资源
竞赛vscode配置指南
What you have to know about network IO model
Take you back to spark ecosystem!
Several silly built-in functions about relative path / absolute path operation in CAPL script
Can I learn PLC at the age of 33