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 2.1.10 学习笔记(2)
    Spring Boot 2.1.10 学习笔记(1)
    Win10 下载与激活 MSDN
    Java JDK 1.8 下载及其版本说明 8u202(最后一个免费版)
    shell函数开发意见优化系统脚本
    php大文件下载支持断点续传
    xunsearch使用笔记
    微信使用的curl方法
    php执行sql语句打印结果
    二维数组排序:array_orderby(php官网评论)
  • 原文地址:https://www.cnblogs.com/zhanggaofeng/p/5450065.html
Copyright © 2011-2022 走看看