c实现功能(7)写入和读取文本文件

#include <stdio.h>
#include <string.h>
int main()
{
    //向一个文件中写入内容
    char s[1024] = {0};
    //打开一个文件
    FILE *p = fopen("D:\\test\\a.txt","w");

    //将信息写入到文件中
    while(1){
        //将数组的内容清0
        memset(s,0,sizeof (s));
        //scanf("%s",s); //这种方式无法输入空格
        gets(s);
        //设置输入的退出模式
        if(strcmp(s,"exit") == 0){
            break;
        }
        //给每行添加换行符
        int len = strlen(s);
        s[len] = '\n';
        fputs(s,p);
    }
    //关闭文件
    fclose(p);
    printf("end\n");
    return 0;
}
#include <stdio.h>
#include <string.h>

int main(){
    //从一个文件中读取内容
    char s[1024] = {0};
    //以只读的方式打开一个文件
    FILE *p = fopen("D:\\test\\a.txt","r");
    //需要判断是否到达文件的末尾
    while(!feof(p)){
        //将数组的内容清0
        memset(s,0,sizeof (s));
        fgets(s,sizeof (s),p);
        printf("%s\n",s);
    }

    fclose(p);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/hc1151310108/article/details/82938163