当前位置:网站首页>My C language learning records (blue bridge) -- files and file input and output
My C language learning records (blue bridge) -- files and file input and output
2022-07-06 02:48:00 【Someone -jojo】
File and file input and output
What is a document
There are different types of documents , In programming , It mainly uses two kinds of documents :
Program files : Include source files ( The suffix is .c), Target file ( The suffix is .o) And executable files . The content of this file is program code .
Data files : The content of the document is not a program , It's data for reading and writing when the program is running , Including the data output to the disk during the program operation and the data for reading during the program operation , Such as the grade data of the whole class 、 Data of goods transaction, etc .
What we discuss in this section is Data files . In order to simplify users' understanding of input and output devices , Users do not have to distinguish between various input and output devices , operating system Treat all kinds of equipment as documents . For example, the terminal keyboard is an input file , The display and printer are output files .
Classification of documents
According to the organization of data , Data files can be divided into ASCII Files and binaries . Data is stored in binary form in memory , If output to external memory without conversion , Binary files , It can be considered as the image of memory data , Called image file . If it is required to use... In external memory ASCII Code storage , It needs to be converted before storage .ASCII Files are also called text files , One character per byte ASCII code .
use ASCII When outputting in code form, bytes and characters correspond one by one , A byte represents a character , So it's easy to process characters one by one , It's also easy to output characters . But it usually takes up more storage space , And it takes time to switch . Output values in binary form , It can save external storage space and conversion time , Output the contents of the storage unit in the memory intact to the external memory disk , At this time, a byte does not necessarily represent a character .
Open and close files
You should “ open ” This document , After use “ close ” file . actually , The so-called opening a file refers to establishing a corresponding information area for the file ( Used to store information about documents ) And file buffers ( Used to temporarily store input and output data ).
fopen() Function to open a data file
fopen() The function is called in **fopen( file name , How to use files );**.
for example :
fopen("a1","r");
To open a computer with a name of “ a1 ” The file of , The way to use files is “ Read in ”(r representative read, Read in ).fopen The return value of the function points to a1 Pointer to file ( namely a1 The starting address of the file information area ). Will usually fopen The return value of the function is assigned to a pointer variable pointing to the file . Such as :
FILE *fp;
fp = fopen("a1","r");
such fp On and file a1 It's connected , Or say fp Yes a1 file .
fclose() Function to close the data file
After using a file, you should close it , To prevent it from being misused .“ close ” Is to undo the file information area and file buffer , Make the file pointer variable no longer point to the file .
fclose() How to call function :**fclose( The file pointer );**.
for example :
fclose(fp);
If you don't close the file, you will lose data , You should get into the habit of closing all files before the program terminates .
Read and write data files in sequence
After opening the file , You can read and write it . When writing in sequence , The data written first is stored in the front of the file , The data written later is stored in the later position in the file . In sequential reading , The order of reading data is consistent with the physical order of data in the file . Sequential reading and writing needs to be realized by library functions .
The function of reading or outputting a character to a text file is shown in table :
Function name | Call form | function | Return value |
fgetc | fgetc(fp) | from fp The file pointed to reads a character | success , Bring back the characters you read ; If it fails, the end of file flag EOF( namely -1) |
fputc | fputc(ch,fp) | Alphabet character ch Write file pointer variable fp In the file pointed to | Output success , The return value is the output character ; Output failed , Then return to EOF( namely -1) |
explain
fgetc First letter of f For documents (file), In the middle of the get Said to get , the last one c According to the character char.fputc Also similar .
Enter some characters from the keyboard , Send them to disk one by one , Until the user enters a “ # ” until .
Their thinking
use fgetc Function to enter characters one by one from the keyboard , And then use fputc Function to write to a disk file .
establish 12-1.c File and enter the following code :
#include<stdio.h>
#include<stdlib.h> // stdlib The header file is standard library Standard library header file
int main(){
FILE * fp;
char ch,filename[10];
printf("Please enter the file name:");
scanf("%s",filename);
// If the file doesn't exist ,fopen The file will be created
if((fp=fopen(filename,"w"))==NULL){ // Open the output file and make fp Point to this file
printf("Unable to open this file\n"); // If there is an error opening , It outputs “ Cannot be opened ” Information about
exit(0); // To terminate the program
}
ch=getchar(); // Used to receive the last entered carriage return
printf("Please enter a string in the disk(Ends with a #):");
ch=getchar(); // Receive the first character entered from the keyboard
while(ch!='#'){ // When the input # End cycle at
fputc(ch,fp);
putchar(ch);
ch=getchar();
}
fclose(fp);
putchar(10);
return 0;
}
Enter the following command to compile and run :
gcc -o 12-1 12-1.c
./12-1
Enter the following command to view the file file_name The content of :
cat /home/project/file_name
The program runs as follows :
Program analysis :
- exit Exist in the standard C In the library function of , The function is to terminate the program , When using this function, the beginning of the program should contain stdlib.h The header file .
- The execution process is as follows : First read a character from the keyboard , Check if it is “ # ”, If it is , Indicates the end of the string , Do not execute loop body . If not , Then execute the loop body , Output this character to file.date . Then the character is displayed on the screen , Then read a character from the keyboard . So again and again , Until it appears “ # ” Until the character . At this time, the program has “ hello shiyanlou ” Write with “ file.date ” In named file .
Read and write data files randomly
It's easier to read and write files in sequence , It's also easy to operate , But it's not efficient . For example, the documents contain information about millions of people in a city , We want to find someone , In order to read and write, you need to read in the first data one by one , The waiting time is unbearable .
To solve this problem , Move the position pointer inside the file to the position where you need to read and write , Read and write again , This kind of reading and writing is called random reading and writing . Random access is not read and write according to the physical location of data in the file , It can access data from any location , Obviously, this method is much more efficient than sequential access .
The key to random reading and writing is to move the position pointer as required , That is, the location of the file .
There are two main functions to move the position pointer inside the file , namely rewind() and fseek().
rewind() The call form of the function is :**rewind( The file pointer );**, Its function is to move the position pointer inside the file to the beginning of the file .
Here is the main introduction fseek function .fseek Function is used to move the position pointer inside the file , Its calling form is :**fseek( The file pointer , Displacement , The starting point );**.
among :“ The file pointer ” Point to the moved file ;“ Displacement ” Represents the number of bytes moved , The required displacement is long Type data , So that when the file length is greater than 64KB There will be no error when , When the displacement is represented by a constant , Suffix is required “ L ”;“ The starting point ” Indicates where to calculate the displacement , There are three starting points specified : File header , Current location and end of file .
Its expression is shown in the following table :
The starting point | A symbol | Digital representation |
File header | SEEK_SET | 0 |
The current position | SEEK_CUR | 1 |
end of file | SEEK_END | 2 |
for example :
fseek(fp,100L,0);
The meaning is to move the position pointer away from the beginning of the file 100 Bytes .
It should also be noted that fseek Functions are generally used in binary files . In the text file due to the need for conversion , Therefore, errors often occur in the calculated position .
Homework
Copy the contents of the file
Introduce
Achieve one C Language program , It can support the simplest replication function .
Knowledge point
- Linux Next C Language programming
- C Language foundation
- C Program input and output processing
- C Language file operation
For example, make a copy /etc/protocols File to /tmp Catalog , The effect of program execution after compilation is as follows :
# compile
$ gcc copy.c -o copy
# function
$ ./copy /etc/protocols /tmp/protocols
Note that the copied file and the target file should be passed in as parameters of the compiled executable file , instead of scanf()
Read , If you use scanf()
Reading will cause the test system to wait for timeout .
The fragments of program parameter processing are as follows :
#include <stdlib.h>
#include <stdio.h>
int main(int argc, char *argv[]){
//...
}
The goal is
- In the experimental building environment on the right WebIDE Create a new document in , Name it copy.c;
- Copy the program fragment to the document copy.c in , And supplement documents ;
- Use a file to complete , Do not use separate header files ;
- copy.c You can compile and run in the environment , The compiled executable accepts two parameters , They are the source and target file paths of the copy ;
- There are two kinds of errors to deal with : The copied source file does not exist , Or the copied target file already exists . When an error occurs, you need to print a with error Output information of .
Refer to the answer
#include<stdio.h>
#include<stdlib.h>
int main(int argc,char **argv){ //tips: main Functions should be able to receive parameters on the command line
if(argc<3)
return 1;
// Get the file name
char* file1 = argv[1];
char* file2 = argv[2];
FILE *fp1,*fp2;
char ch;
// Read source file
if((fp1=fopen(file1,"r"))==NULL)
printf("File isn't exist!\n");
// Create destination file
if((fp2=fopen(file2,"w"))==NULL)
printf("File can't be created!\n");
// Read and write files
while((ch=fgetc(fp1))!=EOF)
fputc(ch,fp2);
fclose(fp1);
fclose(fp2);
return 0;
}
copy
边栏推荐
- Patch NTP server at the beginning of DDoS counterattack
- Shell脚本更新存储过程到数据库
- 球面透镜与柱面透镜
- 微服务注册与发现
- Universal crud interface
- Zhang Lijun: penetrating uncertainty depends on four "invariants"
- 不赚钱的科大讯飞,投资价值该怎么看?
- 【 kubernets series】 a Literature Study on the Safe exposure Applications of kubernets Service
- Apt installation ZABBIX
- 一个复制也能玩出花来
猜你喜欢
[Yunju entrepreneurial foundation notes] Chapter II entrepreneur test 6
[Yunju entrepreneurial foundation notes] Chapter II entrepreneur test 8
XSS challenges绕过防护策略进行 XSS 注入
Yyds dry inventory comparison of several database storage engines
RobotFramework入门(一)简要介绍及使用
Is there a completely independent localization database technology
Httprunnermanager installation (III) - configuring myql Database & initialization data under Linux
C language - Blue Bridge Cup - promised score
[Yunju entrepreneurial foundation notes] Chapter II entrepreneur test 14
[Yu Yue education] basic reference materials of digital electronic technology of Xi'an University of Technology
随机推荐
Looking at the trend of sequence modeling of recommended systems in 2022 from the top paper
会员积分营销系统操作的时候怎样提升消费者的积极性?
[Yunju entrepreneurial foundation notes] Chapter II entrepreneur test 14
Apt installation ZABBIX
解决:AttributeError: ‘str‘ object has no attribute ‘decode‘
Introduction to robotframework (II) app startup of appui automation
2.13 simulation summary
How to improve the enthusiasm of consumers when the member points marketing system is operated?
Dachang image library
[untitled] a query SQL execution process in the database
MySQL winter vacation self-study 2022 11 (7)
Accident index statistics
DDoS "fire drill" service urges companies to be prepared
QT release exe software and modify exe application icon
在GBase 8c数据库中使用自带工具检查健康状态时,需要注意什么?
A doctor's 22 years in Huawei
[Yunju entrepreneurial foundation notes] Chapter II entrepreneur test 11
Zhang Lijun: penetrating uncertainty depends on four "invariants"
2022.02.13
[Yunju entrepreneurial foundation notes] Chapter II entrepreneur test 16