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\n", ERRO_MSG);
        return ERRO_MSG;
    }
    if (pword == NULL)
    {
        ERRO_MSG = 2;
        printf("pword==NULL erro msg:%d\n", 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\n", 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\n", ERRO_MSG);
        return ERRO_MSG;
    }
    if (pout == NULL)
    {
        ERRO_MSG = 2;
        printf("pout==NULL erro msg:%d\n", 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\n", 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] = '\0';
    return ERRO_MSG;
}


void main(){
    //定义文件路径
    char *path = "E:\\Test\\CwordTest\\";//只适用于window
    char *path1 = "E:/Test/CwordTest/a1.txt";
    writeWord(path1, "asfasdfasdgafdsgadf\r\nasdfadsadf\r\ndsafgshfetgrhet");
    //1.定义文件缓存数组
    char bufarr[200] = { 0 };
    readtxt(path1, bufarr);
    printf("%s\n", bufarr);
    system("pause");
}

 

posted on 2016-05-01 09:37  寒魔影  阅读(455)  评论(0编辑  收藏  举报

导航