日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 >

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

發(fā)布時(shí)間:2025/4/16 45 豆豆
生活随笔 收集整理的這篇文章主要介紹了 c语言复习笔记(2)--标准库中的I/O 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

我們?cè)赾語言中的HelloWorld就直接使用了stdio.h中的printf, 在stdio中還有與之對(duì)應(yīng)的scanf

本篇文章中, 主要介紹了fputs和fgets, putc和getc, puts和gets. 并用他們實(shí)現(xiàn)了一個(gè)簡單的echo.

1. fputs和fgets

在stdio中還有很多函數(shù)很有用的, 下面是一個(gè)簡單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是一個(gè)回顯函數(shù), 其中使用了fgets和fputs兩個(gè)函數(shù)

fgets是用來讀取某個(gè)文件流中的數(shù)據(jù)的.

#include <stdio.h>
char *fgets( char *str, int num, FILE *stream ); fgets中有三個(gè)參數(shù), c風(fēng)格的字符串str是用來保存讀取的結(jié)果, num是表示要讀取的字符個(gè)數(shù), stream是文件指針

fputs是用來輸出數(shù)據(jù)到指定文件流的. #include <stdio.h>
int fputs( const char *str, FILE *stream );

fputs有兩個(gè)參數(shù), 第一個(gè)是要輸出的字符串str, 第二個(gè)是文件指針

默認(rèn)的三個(gè)文件指針

標(biāo)準(zhǔn)文件指針FILE *stdin,*stdout,*stderrstdin 指鍵盤輸入stdout 指顯示器stderr 指出錯(cuò)輸出設(shè)備,也指顯示器 如果想把數(shù)據(jù)寫入文件tmp, 可以自己定義一個(gè)文件指針, 然后打開文件
#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, 然后運(yùn)行此程序, 可以看到tmp文件中寫入了數(shù)據(jù)

2. putc和getc

還有putc和getc函數(shù), 也可以使用他們實(shí)現(xiàn)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函數(shù)的版本

#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;
}

關(guān)于EOF的說明:

在windows下, EOF需要輸入組合鍵ctrl+Z, 然后回車, 可以看到程序退出

在linux下, EOF需要輸入組合鍵ctrl+D

轉(zhuǎn)載于:https://www.cnblogs.com/icejoywoo/archive/2011/05/10/2042318.html

《新程序員》:云原生和全面數(shù)字化實(shí)踐50位技術(shù)專家共同創(chuàng)作,文字、視頻、音頻交互閱讀

總結(jié)

以上是生活随笔為你收集整理的c语言复习笔记(2)--标准库中的I/O的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。