当前位置:网站首页>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);
#endif
Project 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");
}
边栏推荐
- 在CANoe中通过Panel面板控制Test Module 运行(高级)
- May brush question 03 - sorting
- Automation sequences of canoe simulation functions
- Keep these four requirements in mind when learning single chip microcomputer with zero foundation and avoid detours
- Southwest University: Hu hang - Analysis on learning behavior and learning effect
- CANoe CAPL文件操作目录合集
- 018. Valid palindromes
- I2C summary (single host and multi host)
- MapReduce instance (x): chainmapreduce
- tn-c为何不可用2p断路器?
猜你喜欢
Control the operation of the test module through the panel in canoe (primary)
[CV] target detection: derivation of common terms and map evaluation indicators
CAPL 脚本对.ini 配置文件的高阶操作
I2C summary (single host and multi host)
C#/. Net phase VI 01C Foundation_ 01: running environment, process of creating new C program, strict case sensitivity, meaning of class library
AI的路线和资源
Notes of Dr. Carolyn ROS é's social networking speech
Why can't TN-C use 2p circuit breaker?
Selection of software load balancing and hardware load balancing
Installation de la pagode et déploiement du projet flask
随机推荐
为什么大学单片机课上51+汇编,为什么不直接来STM32
Vh6501 Learning Series
I2C summary (single host and multi host)
[one click] it only takes 30s to build a blog with one click - QT graphical tool
单片机如何从上电复位执行到main函数?
Why can't TN-C use 2p circuit breaker?
vscode 常用的指令
Selection of software load balancing and hardware load balancing
MapReduce instance (VIII): Map end join
PR 2021 quick start tutorial, first understanding the Premiere Pro working interface
Hero League rotation map automatic rotation
Release of the sample chapter of "uncover the secrets of asp.net core 6 framework" [200 pages /5 chapters]
What you have to know about network IO model
Configure system environment variables through bat script
33岁可以学PLC吗
如何让shell脚本变成可执行文件
Contrôle de l'exécution du module d'essai par panneau dans Canoe (primaire)
通过bat脚本配置系统环境变量
C杂讲 文件 初讲
max-flow min-cut