c语言复习笔记(2)标准库中的I/O

我们在c语言中的HelloWorld就直接使用了stdio.h中的printf, 在stdio中还有与之对应的scanf

本篇文章中, 主要介绍了fputs和fgets, putc和getc, puts和gets. 并用他们实现了一个简单的echo.

1. fputs和fgets

在stdio中还有很多函数很有用的, 下面是一个简单echo的程序

#include <stdio.h>
#include
<stdlib.h>

#define MAXLINE 4096

int main (void)
{
char buf[MAXLINE];

while (fgets(buf, MAXLINE, stdin) != NULL)
{
if (fputs(buf, stdout) == EOF)
{
printf(
"output error\n");
}
}

if (ferror(stdin))
{
printf(
"input error");
}

system(
"pause");
return 0;
}

echo是一个回显函数, 其中使用了fgets和fputs两个函数

fgets是用来读取某个文件流中的数据的.

#include <stdio.h>
char *fgets( char *str, int num, FILE *stream );
fgets中有三个参数, c风格的字符串str是用来保存读取的结果, num是表示要读取的字符个数, stream是文件指针

fputs是用来输出数据到指定文件流的.
#include <stdio.h>
int fputs( const char *str, FILE *stream );

fputs有两个参数, 第一个是要输出的字符串str, 第二个是文件指针

默认的三个文件指针

标准文件指针

   FILE *stdin,*stdout,*stderr
   stdin 指键盘输入
   stdout 指显示器
   stderr 指出错输出设备,也指显示器 
如果想把数据写入文件tmp, 可以自己定义一个文件指针, 然后打开文件
#include <stdio.h>
#include
<stdlib.h>

int main(void)
{
FILE
*fp;

fp
= fopen("tmp", "w");

char *buf = "Hello, World!";

if (fputs(buf, fp) == EOF)
printf(
"output error");

fclose(fp);

system(
"pause");
return 0;
}

在源代码文件的目录下, 建立文件tmp, 然后运行此程序, 可以看到tmp文件中写入了数据

2. putc和getc

还有putc和getc函数, 也可以使用他们实现echo

#include <stdio.h>
#include
<stdlib.h>

int main (void)
{
int c;

while ((c = getc(stdin)) != EOF)
{
if (putc(c, stdout) == EOF)
{
printf(
"output error\n");
}
}

if (ferror(stdin))
{
printf(
"input error");
}

system(
"pause");
return 0;
}

3. puts和gets

puts和gets函数的版本

#include <stdio.h>
#include
<stdlib.h>

#define MAXLINE 4096

int main (void)
{
char str[MAXLINE];

while (gets(str) != NULL)
{
if (puts(str) == EOF)
{
printf(
"output error\n");
}
}

if (ferror(stdin))
{
printf(
"input error");
}

system(
"pause");
return 0;
}

关于EOF的说明:

在windows下, EOF需要输入组合键ctrl+Z, 然后回车, 可以看到程序退出

在linux下, EOF需要输入组合键ctrl+D

原文地址:https://www.cnblogs.com/icejoywoo/p/2042318.html