C 文件 fputs()和fgets() - C语言教程

由网友 大卫 发布 阅读 1

C 文件 fputs()和fgets() - C语言教程

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

C 文件 rewind() 函数 C 语言文件读写