当前位置:网站首页>C primer plus learning notes - 3. Character IO (input / output)
C primer plus learning notes - 3. Character IO (input / output)
2022-06-26 19:54:00 【Charles Ren】
List of articles
getchar() and putchar()
The last chapter introduced printf and scanf Functions belong to IO function .
Here we introduce two functions getchar() and putchar() For characters IO.
explain
getchar() The function takes no arguments , If the buffer is empty , Will wait for the buffer , When you enter and press enter , The next character will be returned from the input queue .
putchar() Function to print the input parameters .
getchar() The function interprets each character as a character code , and scanf() Function looks at input in the same way as it reads characters , But he will convert the character input into the corresponding numerical value according to the conversion instructions .
give an example : Read one line of input string
such as :
#include <stdio.h>
int main(void)
{
char ch;
ch = getchar(); // read a character
putchar(ch); // print the newline
return 0;
}
If I type... On the keyboard abcd agf And then go back , Then the print will be a.
because getchar() Will read a line we entered Enter enter to end , Spaces do not end .
Then he will read the next character ( That's the first one ) And assign it to ch
putchar() take ch Print out .
Look at the following procedure :
int main(void)
{
char ch;
ch = getchar(); // read a character
while (ch != '\n') // while not end of line
{
putchar(ch);
ch = getchar(); // get next character
}
putchar(ch); // print the \n
return 0;
}
When we type in ndn ang And then go back , prints ndn ang.
Look at the :
- When we enter the string, press enter , The actual input is
ndn ang\nIndicates that one line of input is complete . - ch At this time, the first character of the input is read
- Then judge , It's not a newline , Will print ,
- Call again after printing getchar() It means to read the next character in the queue just entered .
- Then judge whether it is a newline character , No more printing , By analogy .
The above code can be abbreviated , Replace cycle
int main(void)
{
char ch;
while ((ch = getchar()) != '\n') // while not end of line
{
putchar(ch);
}
return 0;
}
In the above example, we can read a line of input string with spaces .
We can also end with a specific character
while ((ch = getchar()) != '#') // while not end of line
So when we enter
angn asdn#dng
Will get
angn asdn
buffer
Buffered and unbuffered
In the above example, we find that , When we enter a line of string ndn ang Only when we hit enter , The program will print . If we don't hit enter, we can always enter . This input is called Make buffered input .
So where are the input strings . The characters entered by the user are collected in a storage location called buffer .
But when we play games , We press a key , There will be an immediate response , Like release q Skill . This is called Unbuffered input . Therefore, buffered input and unbuffered input have their own application scenarios .
ANSI C And subsequent C The standard specifies that the input is buffered , But at first C The input in the standard is unbuffered .
Buffer classification
There are two types of buffers : Completely buffered IO And line buffering IO.
- Completely buffered : The buffer is flushed only when it is full ( That is, send the content to the destination and empty the buffer ). It usually appears in file input , The buffer size usually depends on the 512B or 4K.
- The line buffer : This means that the buffer is flushed when a line break occurs ( That is, send the content to the destination and empty the buffer ). Keyboard entry Usually line buffered input , Press down Enter Key before refreshing the buffer .
Keyboard input Terminator
In the example above , We use carriage return to end , The other is to use ‘#’ Symbol to end the program .
These symbols are commonly used , We should not end the program with common symbols . So we should find a way to end it with a relatively unique thing ,C Such a character is provided .
file
Let's briefly introduce the concept of file , It is the area of memory where information is stored .
Programs often manipulate files , Like opening , Read , Turn off writing, etc .
Why use unification C standard IO
C The language will call the underlying IO That is, operating system functions operate on files . such as linux System function write() open() etc. .
But if windows On , Call directly write() open No way. , Need to call windows The system function of . therefore C Language encapsulates the file processing functions of different systems into C Standards for IO package . He deals with the differences between different systems , Expose unified functions to users, such as fopen(),fwrite() etc. .
Handling file differences
Different systems not only expose different file handling functions , They also deal with documents in different ways . For example, some systems store the contents of files in one place , File related information is stored in another place . Some systems create special file descriptions in each file .
Different systems also end with different files .
C How to process input
C Treat keyboard input and output as automatically opened files .stdin Represents keyboard input ,stdout Indicates output to the screen .
That is to say C Handle keyboard input by processing files .
for example , When the program reads a file, it needs to check the end of the file to know when to stop . Keyboard input is a file , When you enter what character , The program will detect and stop .
End of file
A few systems use Ctrl+Z. such as ngnag ^Z, The system reads Ctrl+Z ends .
Other systems store file size information , If the document has 300 byte , Then the program is finished 300 Bytes later, it will stop . such as Unix System .
getchar() When the end of the file is detected, a EOF. He -1 The macro definition of , stay stdio.h In file .#define EOF (-1)
because getchar() Itself returns the next character read ,-1 As he reads the Terminator .
int main(void)
{
int ch;
while ((ch = getchar()) != EOF) // while not end of line
{
putchar(ch);
}
return 0;
}
because EOF yes -1 So the variable ch To be changed to int, and getchar() The actual return type is also int.
The above example , Let's enter a line , Press enter , Will flush the buffer . Program getchar() It will read in the input line in turn and print .
Continue to wait for input after printing .
In most Unix and Linux The system will use Ctrl+D As input Terminator .
asdn aslkd
asdn aslkd
aghn
aghn
Redirect
Redirection is a command line concept , instead of C Concepts in programs .
We said earlier stdin It's the input stream , We use keyboard input as input and stdin The input stream is associated with .
We can also use the contents of the file as stdin Input stream , such getchar() Functions can also use .
The program doesn't care whether the input comes from the keyboard or from a file , All he knows is that this is the character stream to be imported
Redirect input :
We can use programs to read files 1.txt./echo_eof < 1.txt
int main(void)
{
int ch;
while ((ch = getchar()) != EOF) // while not end of line
{
putchar(ch);
}
return 0;
}
Because there will be a terminator at the end of the file , So the program can read the end symbol and then end .
Redirect output
./echo_eof > 1.txt He will output the program to 1.txt In file
Combined redirection
For example, I read a file , Enter the program , Then the program input to another file ./echo_eof < in.txt > out.txt./echo_eof > out.txt < in.txt
The above two sentences are the same , Because redirection symbols have no order .
边栏推荐
- Reading notes: process consulting III
- 关于Qt数据库开发的一些冷知识
- 【Kubernetes】Kubernetes 原理剖析与实战应用(更新中)
- Solidity - contract inheritance sub contract contains constructor errors and one contract calls the view function of another contract to charge gas fees
- Installation and use of logstash
- Unity——Mathf. Similarities and differences between atan and atan2
- 710. 黑名单中的随机数
- Microservice architecture
- 微服务版单点登陆系统(SSO)
- C exercise. Class list plus records, display records and clear records
猜你喜欢

Kubernetes resource topology aware scheduling optimization

回溯思路详解

一些基本错误

When does the mobile phone video roll off?

Create a time blocker yourself

Daily basic use of alicloud personal image warehouse

Some cold knowledge about QT database development

mysql的充值问题

Feign remote call

Preliminary analysis of serial port printing and stack for arm bare board debugging
随机推荐
刷新三观的HP-UX系统中的强指针赋值出core问题
Résolution du problème: la machine virtuelle n'a pas pu copier et coller le fichier
Tiktok practice ~ search page ~ video details
品达通用权限系统(Day 1~Day 2)
关于Qt数据库开发的一些冷知识
Is it safe to open an account for CICC Wealth Online?
抖音实战~分享模块~生成短视频二维码
To: Apple CEO Cook: great ideas come from constantly rejecting the status quo
(几何) 凸包问题
C primer plus学习笔记 —— 3、字符的IO(输入/输出)
IK word breaker
Boot指标监测
Some basic mistakes
Summary of several common UML diagrams
When are global variables initialized before entering the main function?
tsconfig. json
抖音实战~搜索页面~扫描二维码
Unity - URP get camera stack
Super VRT
C# 练习。类列表加记录,显示记录和清空记录