格式化的行I/O:
scanf函数族:从输入中读取值存储在指针参数指向的内存的位置。
int scanf(char *format, &...);
int ssanf(char *string, char *format, &...);
int fscanf(FILE *fp, char *format, &...); 正确返回读取的值得个数,错误返回EOF;
printf函数族:用于创建格式化的输出。
int printf(char *format, ...);
int fprintf(FILE *fp, char *format, ...);
int sprintf(char *buffer, char *format, ...); 正确返回打印的值得个数,错误返回EOF;
#include <stdio.h>
#include <stdlib.h>
#define MAX_LINE 50
int my_sscanf(void); /*sscanf、sprintf函数*/
int my_fscanf(void); /*fscanf、fprintf函数*/
int main(int argc, char *argv[])
{
my_sscanf();
my_fscanf();
return 0;
}
int my_sscanf() /*sscanf、sprintf函数*/
{
char *string = "8080 abc";
int num = 0;
char array[MAX_LINE] = {0};
char buffer[MAX_LINE] = {0};
sscanf(string, "%d %s", &num, array); /*以空格换行符作为一个数据结束*/
printf("num : %d num1 : %s\n", num, array);
sprintf(buffer, "this is sprintf buffer:%d", num);/*固定格式输入到buffer里面*/
printf("sprintf buffer: %s\n", buffer);
return 0;
}
int my_fscanf() /*fscanf、fprintf函数*/
{
char buffer1[MAX_LINE] = "aaaaa bbbbb 11111 99999 hahahahaha";
char buffer2[MAX_LINE] = {0};
FILE *file = NULL;
int ret = 0;
file = fopen("file.txt", "w+");
if(file == NULL){
perror("fopen error: ");
exit(EXIT_FAILURE);
}
fprintf(file, "%s", buffer1); /*将buffer内的数据全部输出到文件流中*/
fclose(file);
file = fopen("file.txt", "a+");
if(file == NULL){
perror("fopen error: ");
exit(EXIT_FAILURE);
}
fscanf(file, "%s", buffer2); /*遇到空格或者换行符,会停止*/
printf("fprintf buffer2: %s\n", buffer2);
fclose(file);
return 0;
}
关于I/O流函数还有很多,此次统阔到这里,以后边遇到边学习积累。