当前位置:网站首页>It's hard to hear C language? Why don't you take a look at my article (7) input and output
It's hard to hear C language? Why don't you take a look at my article (7) input and output
2022-06-24 22:53:00 【The Great Gatsby.】
1. Write it at the front
The previous blog , I've already introduced myself C Some basic information about language . Including variable 、 control flow 、 function 、 The pointer 、 Structure and so on . We learn Java Of all know ,Java There are many frameworks in powerful places , There's a lot of API For us to use .C It's an old language , It has its powerful API, It is hidden in the corresponding header file , In this blog, let's introduce C Standard input and output of language .
2. The standard input / Output
The standard library implements simple text input / The output mode . A text stream consists of a series of lines , At the end of each line is a newline character . If the system does not follow this pattern , The standard library will adopt some measures to adapt to this mode .
The simplest input mechanism is to use getchar Function from standard input once Read A character :
int getchar(void)
getchar The function returns the next input character each time it is called . If the end of the file is encountered , Then return to EOF. Symbolic constant EOF In the header file <stdio.h> In the definition of , Its value is generally -1, But the program should use EOF To test whether the file ends , Only in this way can we ensure that the procedure is the same as EOF Is independent of the specific value of .
function
int putchar(int)
be used for Output data .putchar The character c To the standard output , By default , Standard output is screen display . If nothing goes wrong , The function putchar The output character will be returned ; If something goes wrong , Then return to EOF. Again , usually , You can also use "> Output file name " Redirect output to a file in the format of .
Let's look at the following procedure , The details are as follows :
#include <stdio.h>
#include <ctype.h>
main() /* lower: convert input to lower case*/
{
int c;
while ((c = getchar()) != EOF)
putchar(tolower(c));
return 0;
}
The above program is a simple file input and output function , By entering data from the console , Then output to the console , At the same time, these data have been converted to lowercase . The other letters are output as is .
3. Format output -printf function
The format string contains two types of objects : Ordinary characters and conversion instructions . At output time , Common stock characters are copied to the output stream as is , The transformation specification is not output directly to the output stream , It's used to control printf Conversion and printing of parameters in , Each conversion description consists of a percent character (%) Start , And results in a converted character . In the character % And conversion characters may contain the following components in turn :
- Minus sign , Used to specify that the converted parameters are output in the form of left alignment .
- Count , Used to specify the minimum field width . The converted parameters will print fields that are not less than the minimum field width .
- decimal point , Used to separate field width from precision .
- Count , Used to specify the precision , That is, specify the maximum number of characters to be printed in the string 、 Floating point number the number of digits after the decimal point 、 The number of integer minimum output digits
- Letter h or l, Letter h The table does not treat integers as short Type print , Letter l Indicates that an integer is taken as long Type print .
printf Basic conversion description of function
| character | Parameter type : Output form |
|---|---|
| d,i | int type : Decimal number |
| o | int type : Unsigned octal |
| x,X | int type : Unsigned hexadecimal number |
| u | int type : An unsigned decimal number |
| c | int type : Single character |
| s | char * type , Print the characters in the string sequentially , until ’\0’ Or the number of characters specified by precision has been printed |
| f | double type : Decimal number |
| e,E | double type |
| g,G | double type |
| p | void * type , The pointer |
| % | Do not convert parameters : Print a percent sign % |
function sprintf Executed transformations and functions printf identical , But it saves the output to a string
int sprintf(char *string, char *format, arg1, arg2, ...);
sprintf Functions and printf The function is the same , according to format Format format parameter sequence arg1、arg2、…, But it stores the output in string in , Instead of exporting to standard output .
4. Variable length parameter table
In this section, we mainly look at the corresponding printf Function our own implementation , The details are as follows :
#include <stdio.h>
#include <stdarg.h>
/* minprintf: minimal printf with variable argument list */
void minprintf(char *fmt, ...) {
va_list ap; /* points to each unnamed arg in turn */
char *p, *sval;
int ival;
double dval;
va_start(ap, fmt); /* make ap point to 1st unnamed arg */
for (p = fmt; *p; p++) {
if (*p != '%') {
putchar(*p);
continue;
}
switch (*++p) {
case 'd':
ival = va_arg(ap, int);
printf("%d", ival);
break;
case 'f':
dval = va_arg(ap, double);
printf("%f", dval);
break;
case 's':
for (sval = va_arg(ap, char *); *sval; sval++)
putchar(*sval);
break;
default:
putchar(*p);
break;
}
}
va_end(ap); /* clean up when done */
}
among , Ellipsis indicates that the number and type of parameters in the parameter table are variable . Ellipsis can only appear at the end of the parameter table .
va_list Type is used to declare a variable , This variable references each parameter in turn . In function minprintf in , We call this variable ap, Parameter pointer . macro va_start take ap Initialize to a pointer to the first unnamed parameter . In the use of ap Before , The macro must be called once , The parameter table must contain at least one named parameter ,va_start Take the last named parameter as the starting point .
Every time you call va_arg, This function will return a parameter , And will ap Point to the next parameter .va_arg Use a type name to determine the type of object returned 、 Step of pointer movement . Last , Must be called before the function returns va_end, To complete some necessary cleaning work .
5. Format input -scanf function
scanf Function reads a character sequence from standard input , according to format The format description in explains the character sequence , And save the results to the rest of the parameters .
When scanf Function scans its format string , Or when some input cannot match the format control description , The function will terminate , meanwhile , The number of input items successfully matched and assigned will be returned as the function value , therefore , The return value of this function can be used to determine the number of input items that have been matched . If you reach the end of the file , This function will return EOF.
There is also an input function sscanf, It is used from a string ( Instead of standard input ) Read character sequence in :
int sscanf(char *string, char *format, arg1, arg2, ...)
It follows the format parameters format Scan string in the format specified in string, And save the results to arg1、arg2 Of these parameters , These parameters must be pointers . The specific format is as follows :
| character | Parameter type : Output form |
|---|---|
| d | int type : Decimal number |
| i | integer :int * type , It can be octal or hexadecimal |
| o | int type : Unsigned octal |
| u | int type : An unsigned decimal number |
| x | int type : Unsigned hexadecimal number |
| c | character :char * type , Enter the next multiple characters ( The default is 1 Characters ) Store in the designated location , This conversion specification usually does not skip whitespace . If you need to read in the next non blank character , have access to %1s |
| s | character string ( Without quotes )char * type , Point to a string large enough to hold the string ( It also includes trailing characters ’\0’) Array of characters , A terminator will be added to the end of the string ’\0’ |
| e,f,g | Floating point numbers , It can include a sign decimal point Index part float* type |
| % | character %: No assignment operation |
6. File access
The file pointer , It points to a structure that contains file information , This information includes : Buffer location 、 The position of the current character in the buffer 、 Read or write status of the file 、 Whether there is an error or whether the end of the file has been reached .
Open a file as follows :
fp = fopen(name, mode);
fopen The first argument to is a string , It contains the file name . The second parameter is the access mode , Also a string , Used to specify how files are used . The allowed modes are : read (“r”)、 Write (“w”) And add (“a”). Some systems also distinguish between text files and binary files , Access to the latter requires adding characters to the schema string " b";
If you open a nonexistent file for writing or appending , The change file will be created . When opening an existing file in write mode , The original contents of the file will be overwritten . however , If you open a file by appending , The original contents of the modified file will remain unchanged .
Let's look at the following code :
#include <stdio.h>
/* cat: concatenate files, version 1 */
main(int argc, char *argv[]) {
FILE *fp;
void filecopy(FILE *, FILE *);
if (argc == 1) /* no args; copy standard input */
filecopy(stdin, stdout);
else
while (--argc > 0)
if ((fp = fopen(*++argv, "r")) == NULL) {
printf("cat: can't open %s\n, *argv");
return 1;
} else {
filecopy(fp, stdout);
fclose(fp);
}
return 0;
}
/* filecopy: copy file ifp to file ofp */
void filecopy(FILE *ifp, FILE *ofp) {
int c;
while ((c = getc(ifp)) != EOF)
putc(c, ofp);
}
The file pointer stdin And stdout All are FILE * Object of type . But they are constants , Not variables . Therefore, they cannot be assigned .
7. Error handling -stderr and exit
cat The error handling function of the program is not perfect . The problem lies in , If one of the files is inaccessible for some reason , The corresponding diagnostic information can only be printed at the end of the output of the connection . When output to the screen , This treatment is acceptable , But if you export to a file or pipeline to another program , It's unacceptable .
So we modified the following program , The details are as follows :
#include <stdio.h>
#include <stdlib.h>
void exit(int i);
/* cat: concatenate files, version 2 */
main(int argc, char *argv[]) {
FILE *fp;
void filecopy(FILE *, FILE *);
char *prog = argv[0]; /* program name for errors */
if (argc == 1) /* no args; copy standard input */
filecopy(stdin, stdout);
else
while (--argc > 0)
if ((fp = fopen(*++argv, "r")) == NULL) {
fprintf(stderr, "%s: can't open %s\n", prog, *argv);
exit(1);
} else {
filecopy(fp, stdout);
fclose(fp);
}
if (ferror(stdout)) {
fprintf(stderr, "%s: error writing stdout\n", prog);
exit(2);
}
exit(0);
}
The program sends error messages in two ways . First , take fprintf The diagnostic information generated by the function is output to stderr On , Therefore, the diagnostic information will be displayed on the screen , Instead of just exporting to a pipe or output file .
secondly , The program uses standard library functions exit, When a function is called , It will terminate the execution of the calling program .
8. Line input and line output
Let's look directly at the corresponding code , The details are as follows :
/* fgets: get at most n chars from iop */
char *fgets(char *s, int n, FILE *iop)
{
register int c;
register char *cs;
cs = s;
while (--n > 0 && (c = getc(iop)) != EOF)
if ((*cs++ = c) == '\n')
break;
*cs = '\0';
return (c == EOF && cs == s) ? NULL : s;
}
/* fputs: put string s on file iop */
int fputs(char *s, FILE *iop)
{
int c;
while (c = *s++)
putc(c, iop);
return ferror(iop) ? EOF : 0;
}
Standard input functions fgets, It and getline Function similar to .
9. Other functions
9.1 String manipulation functions
The following functions are in <string.h> In the definition of
- strcat(s,t) take t The string pointed to is connected to s To the end of the string .
- strncat(s,t,n) take t In the string pointed to n Characters to s To the end of the string .
- strcmp(s,t) according to s The string pointed to is less than (s<t)、 be equal to (s==t) Or greater than (s>t) t Different situations of the string pointed to , Return negative integers respectively 、0 Or a positive integer .
- strcnmp(s,t,n) Same as strcmp identical , But only before n Compare... In characters .
- strcpy(s,t) take t Copy the string to s Point to .
- strncpy(s, t, n) take t In the string pointed to n Characters copied to s Point to .
- strlen(s) return s The length of the string pointed to
- strchr(s,c) stay s Find... In the string pointed to c, If you find , Returns a pointer to the position where it first appears , Otherwise return to NULL
- strrchr(s,c) stay s Find... In the string pointed to c, If you find , Returns a pointer to the position where it last appeared , Otherwise return to NULL
9.2 Character category test and conversion function
The following functions are in <ctype.h> In the definition of
- isapha if c It's the letters , Return a non 0 value , Otherwise return to 0
- isupper if c It's capital letters , Return a non 0 value , Otherwise return to 0
- islower if c It's lowercase , Return a non 0 value , Otherwise return to 0
- isdigit if c It's an array , Return a non 0 value , Otherwise return to 0
- isalnum if isalpha or isdigit, Return a non 0 value , Otherwise return to 0
- isspace if c Is a space 、 Horizontal tabs 、 A newline 、 A carriage return 、 Page feed or vertical tab Return a non 0 value
- toupper return c In capital form
- tolower return c In lowercase
9.3ungetc function
Format of function :
int ungetc(int c, FILE *fp)
This function converts the character c Write back to the file fp in , If it works , Then return to c, Otherwise return to EOF. Each file can only receive one writeback character .ungetc Function can be used with any input function .
9.4 Command execution function
function system(char* s) The execution is contained in the string s The command . Then continue to execute the current program .
9.5 Storage management functions
function malloc and calloc Used to dynamically allocate storage blocks . The details are as follows
void *malloc(size_t n)
When the allocation is successful , It returns a pointer , Set pointer to n Byte length uninitialized Storage space , Otherwise return to NULL.
void *calloc(size_t n, size_t size)
When the allocation is successful , It returns a pointer , The free space pointed to by this pointer is enough to hold the free space indicated by n An array of objects of specified length . Otherwise return to NULL. The storage space is initialization by 0.
free§ Function to release p Point to the storage space , among ,p It was passed before malloc or calloc Function gets a pointer to .
9.6 Mathematical functions
The following functions are in <math.h> In the definition of
- sin(x) x The sine function of , among x In radians
- cos(x) x Cosine function of , among x In radians
- atan2(y,x) y/x The arctangent function of , among ,x and y In radians
- exp(x) Exponential function ex
- log(x) x The natural logarithm of
- log10(x) x The logarithm of the constant
- pow(x,y) Calculation x Of y The value of the power
- sqrt(x) x The square root of
- fabs(x) x The absolute value of
9.7 Random number generator function
function rand() Build between 0 and RAND_MAX Between the pseudo-random integer sequences . among RAND_MAX Is in header file <stdlib.h> Symbolic constants defined in . The following is a method of generating greater than or equal to 0 But less than 1 Random floating point number method :
#define frand() ((double) rand() / (RAND_MAx + 1.0))
10. At the end
This blog mainly introduces C The standard input and output functions of language , The following chapter mainly introduces UNIX System interface of .
边栏推荐
- CA Zhouji - the first lesson in 2022 rust
- Web攻击之CSRF和SSRF
- Solve the problem of non secure websites requesting localhost to report CORS after chrome94
- 动态菜单,自动对齐
- The core concept of JMM: happens before principle
- Based on the codeless platform, users deeply participated in the construction, and digital data + Nanjing Fiberglass Institute jointly built a national smart laboratory solution
- Wechat side: what is consistent hash? In what scenario? What problems have been solved?
- Kubevela v1.2 release: the graphical operation console velaux you want is finally here
- 上新了,华为云开天aPaaS
- See how sparksql supports enterprise data warehouse
猜你喜欢

2022-06-16 work record --js- judge the number of digits in string type digits + judge the number of digits in numeric type digits + limit the text length (display n words at most, exceeding...)

FANUC机器人_KAREL编程入门学习(1)

See how sparksql supports enterprise level data warehouse

High level application of SQL statements in MySQL database (II)

Learn more about redis' eight data types and application scenario analysis
How to solve the problem that the computer suddenly can't connect to WiFi

Technology inventory: past, present and future of Message Oriented Middleware

【文本数据挖掘】中文命名实体识别:HMM模型+BiLSTM_CRF模型(Pytorch)【调研与实验分析】

Leetcode: push domino (domino simulation)

倍加福(P+F)R2000修改雷达IP
随机推荐
Leetcode: push domino (domino simulation)
【软件工程】期末重点
是否需要提高代码阅读能力?这有技巧
Talk about GC mechanism often asked in interview
Solution to the login error of tangdou people
2022年高处安装、维护、拆除考试模拟100题及模拟考试
See how sparksql supports enterprise level data warehouse
Envoy obtain the real IP address of the client
vulnhub DC: 2
AttacKG: Constructing Technique Knowledge Graph from Cyber Threat Intelligence Reports代码复现
Basic principles of spanning tree protocol
Annotation
In the era of full programming, should I give up this road?
win10或win11打印机无法打印
See how sparksql supports enterprise level data warehouse
The difference between interceptor and filter
Certificate photo processing
CSRF and SSRF for web attacks
机器学习编译入门课程学习笔记第一讲 机器学习编译概述
Solve the problem of port occupation