写文本文件

来源:互联网 发布:软件测试项目心得体会 编辑:程序博客网 时间:2024/05/16 01:27

文件操作

1. 从控制台输入数据,并将其保存到一个文本文件中

函数:

fopen()

#include <stdio.h>

FILE *fopen( const char *fname, const char *mode );

fopen()函数打开由fname(文件名)指定的文件, 并返回一个关联该文件的流.如果发生错误, fopen()返回NULL.mode(方式)是用于决定文件的用途


fputs()

#include <stdio.h>int fputs( const char *str, FILE *stream );
fputs()函数把str(字符串)指向的字符写到给出的输出流. 成功时返回非负值, 失败时返回EOF.

                                                                                                              

#include #include #include int main(){    char s[1024] = {0};    FILE *fp = fopen("D:\\temp\\a.txt","w"); // 以写的方式打开一个文件    while(1)    {        char c;        memset(s,0,sizeof(s));        scanf("%s",s); // 或者将该句改为gets(s);        c=getchar();        if (strcmp(s,"exit")==0)        {            break;        }        if(c =='\n')        {            int len = strlen(s);            s[len] = '\n';        }        if(c == 32)        {            int len = strlen(s);            s[len] = ' ';        }        fputs(s,fp);    }    fclose(fp);    return 0;}


0 0
原创粉丝点击