zoukankan      html  css  js  c++  java
  • C语言 文件操作9--fgetc()和fputc()

    //fgetc()和fputc()
    
    #define _CRT_SECURE_NO_WARNINGS
    #include<stdio.h>
    #include<stdlib.h>
    #include<string.h>
    
    //文本写文件
    int writeWord(const char *path,const char *pword){
        int ERRO_MSG = 0;
        int i = 0;
        if (path == NULL)
        {
            ERRO_MSG = 1;
            printf("path==NULL erro msg:%d
    ", ERRO_MSG);
            return ERRO_MSG;
        }
        if (pword == NULL)
        {
            ERRO_MSG = 2;
            printf("pword==NULL erro msg:%d
    ", ERRO_MSG);
            return ERRO_MSG;
        }
        //定义文件指针
        FILE *fpw=NULL;
        //打开文件
        fpw = fopen(path, "w");//w 打开只写文件,若文件存在,则文件长度清零,即文件内容会消失,若文件不存在则建立该文件
        //判断文件是否打开成功
        if (fpw==NULL)
        {
            ERRO_MSG = 1;
            printf("文件打开失败 fpw==NULL erro msg:%d
    ", ERRO_MSG);
            return ERRO_MSG;
        }
        //开始写文件
        for (i = 0; i < (int)strlen(pword)+1; i++)
        {
            fputc(pword[i], fpw);
        }
        //fputs(pword, fpw);
        //关闭文件
        if (fpw!=NULL)
        {
            fclose(fpw);
        }
        return ERRO_MSG;
    }
    
    //文件读文件
    int readtxt(const char *path,char *pout)//二级指针做输出
    {
        int ERRO_MSG = 0;
        if (path==NULL)
        {
            ERRO_MSG = 1;
            printf("path==NULL erro msg:%d
    ", ERRO_MSG);
            return ERRO_MSG;
        }
        if (pout == NULL)
        {
            ERRO_MSG = 2;
            printf("pout==NULL erro msg:%d
    ", ERRO_MSG);
            return ERRO_MSG;
        }
        //定义文件指针
        FILE *pfr = NULL;
        //打开文件
        pfr = fopen(path, "r");
        if (pfr==NULL)
        {
            ERRO_MSG = 3;
            printf("pfr==NULL erro msg:%d,文件路径:%s
    ", ERRO_MSG, path);
            return ERRO_MSG;
        }
        //开始读文件
        int index = 0;
        //读文件
        while (!feof(pfr)){//feof()如果文件结束,则返回非0值,否则返回0
            //memset(pout, 0, sizeof(char)*200);
            pout[index++] = fgetc(pfr);
        }
        pout[index] = '';
        return ERRO_MSG;
    }
    
    
    void main(){
        //定义文件路径
        char *path = "E:\Test\CwordTest\";//只适用于window
        char *path1 = "E:/Test/CwordTest/a1.txt";
        writeWord(path1, "asfasdfasdgafdsgadf
    asdfadsadf
    dsafgshfetgrhet");
        //1.定义文件缓存数组
        char bufarr[200] = { 0 };
        readtxt(path1, bufarr);
        printf("%s
    ", bufarr);
        system("pause");
    }
  • 相关阅读:
    Spring Boot入门篇(基于Spring Boot 2.0系列)
    webpack性能优化配置
    Vuex的通俗详解
    Vuefilter() 过滤器
    transition页面加载触发问题解决方案
    VUE render VS template
    provide & inject 跨组件传值
    Vue 组件通讯(组件传值)
    js封装 DOM获取
    GIT SVN 版本管理 git + gitHub
  • 原文地址:https://www.cnblogs.com/zhanggaofeng/p/5450065.html
Copyright © 2011-2022 走看看