C fputs()和fgets()基础教程文档

收录于 2023-04-20 00:10:05 · بالعربية · English · Español · हिंदीName · 日本語 · Русский язык · 中文繁體

C编程中的fputs()和fgets()用于从流中写入和读取字符串。让我们看看使用fgets()和fgets()函数编写和读取文件的示例。

写入文件: fputs()函数

fputs()函数将一行字符写入文件。它将字符串输出到流中。
语法:
int fputs(const char *s, FILE *stream)
示例:
#include<stdio.h>
#include<conio.h>
void main(){
FILE *fp;
clrscr();
fp=fopen("myfile2.txt","w");
fputs("hello c programming",fp);
fclose(fp);
getch();
}
myfile2.txt
hello c programming

读取文件: fgets()函数

fgets()函数从文件中读取一行字符。它从流中获取字符串。
语法:
char* fgets(char *s, int n, FILE *stream)
示例:
#include<stdio.h>
#include<conio.h>
void main(){
FILE *fp;
char text[300];
clrscr();
fp=fopen("myfile2.txt","r");
printf("%s",fgets(text,200,fp));
fclose(fp);
getch();
}
输出:
hello c programming