c文件操作之fgets,fputs

来源:互联网 发布:服务器安装mysql数据库 编辑:程序博客网 时间:2024/06/05 08:41
fgetc() 和 fputc() 函数每次只能读写一个字符,速度较慢;实际开发中往往是每次读写一个字符串或者一个数据块,这样能明显提高效率。

读字符串函数fgets

fgets() 函数用来从指定的文件中读取一个字符串,并保存到字符数组中,它的原型为:
char *fgets ( char *str, int n, FILE *fp );
str 为字符数组,n 为要读取的字符数目,fp 为文件指针。

返回值:读取成功时返回字符数组首地址,也即 str;读取失败时返回 NULL;如果开始读取时文件内部指针已经指向了文件末尾,那么将读取不到任何字符,也返回 NULL。

注意,读取到的字符串会在末尾自动添加 '\0',n 个字符也包括 '\0'。也就是说,实际只读取到了 n-1 个字符,如果希望读取 100 个字符,n 的值应该为 101。例如:
复制纯文本复制
  1. #define N 101
  2. char str[N];
  3. FILE *fp = fopen("D:\\demo.txt", "r");
  4. fgets(str, N, fp);
#define N 101char str[N];FILE *fp = fopen("D:\\demo.txt", "r");fgets(str, N, fp);
表示从 D:\\demo.txt 中读取100个字符,并保存到字符数组str中。

需要重点说明的是,在读取到 n-1 个字符之前如果出现了换行,或者读到了文件末尾,则读取结束。这就意味着,不管n的值多大,fgets() 最多只能读取一行数据,不能跨行。在C语言中,没有按行读取文件的函数,我们可以借助 fgets(),将n的值设置地足够大,每次就可以读取到一行数据。

【示例】一行一行地读取文件。
复制纯文本复制
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #define N 100
  4. int main(){
  5. FILE *fp;
  6. char str[N+1];
  7. if( (fp=fopen("d:\\demo.txt","rt")) == NULL ){
  8. printf("Cannot open file, press any key to exit!\n");
  9. getch();
  10. exit(1);
  11. }
  12. while(fgets(str, N, fp) != NULL){
  13. printf("%s", str);
  14. }
  15. fclose(fp);
  16. system("pause");
  17. return 0;
  18. }
#include <stdio.h>#include <stdlib.h>#define N 100int main(){    FILE *fp;    char str[N+1];    if( (fp=fopen("d:\\demo.txt","rt")) == NULL ){        printf("Cannot open file, press any key to exit!\n");        getch();        exit(1);    }       while(fgets(str, N, fp) != NULL){        printf("%s", str);    }    fclose(fp);    system("pause");    return 0;}
将下面的内容复制到 D:\\demo.txt:

C语言中文网
http://c.biancheng.net
一个学习编程的好网站!

那么运行结果为:


fgets() 遇到换行时,会将换行符一并读取到当前字符串。该示例的输出结果之所以和 demo.txt 保持一致,该换行的地方换行,就是因为 fgets() 能够读取到换行符。而 gets() 不一样,它会忽略换行符。

写字符串函数fputs

fputs() 函数用来向指定的文件写入一个字符串,它的原型为:
int fputs( char *str, FILE *fp );
str 为要写入的字符串,fp 为文件指针。写入成功返回非负数,失败返回EOF。例如:
复制纯文本复制
  1. char *str = "http://c.biancheng.net";
  2. FILE *fp = fopen("D:\\demo.txt", "at+");
  3. fputs(str, fp);
char *str = "http://c.biancheng.net";FILE *fp = fopen("D:\\demo.txt", "at+");fputs(str, fp);
表示把把字符串 str 写入到 D:\\demo.txt 文件中。

【示例】向上例中建立的 d:\\demo.txt 文件中追加一个字符串。
复制纯文本复制
  1. #include<stdio.h>
  2. int main(){
  3. FILE *fp;
  4. char str[102] = {0}, strTemp[100];
  5. if( (fp=fopen("D:\\demo.txt", "at+")) == NULL ){
  6. printf("Cannot open file, press any key to exit!\n");
  7. getch();
  8. exit(1);
  9. }
  10. printf("Input a string:");
  11. gets(strTemp);
  12. strcat(str, "\n");
  13. strcat(str, strTemp);
  14. fputs(str, fp);
  15. fclose(fp);
  16. return 0;
  17. }
原创粉丝点击