C/C++学习之C提高-----文件操作,C程序读写文件、配置文件读写案例

来源:互联网 发布:win10优化驱动器 固态 编辑:程序博客网 时间:2024/05/21 11:04

1.文件操作

(1)按字符写入文件

#define  _CRT_SECURE_NO_WARNINGS #include <stdlib.h>#include <string.h>#include <stdio.h>void main(){    int     i = 0;    FILE *fp = NULL;    char *filename2 = "c:/2.txt";      char a[27] = "dsadsadefsfdggsfadqw";    fp = fopen(filename2, "r+"); //读写的方式,打开文件 如果文件不存在,则报错    if (fp == NULL)    {        printf("func fopen() err:%d \n");        return;    }    printf("打开成功\n");    for (i = 0; i < strlen(a); i++)    {        fputc(a[i], fp);    }    printf("写入成功\n");    fclose(fp);    printf("hello...\n");    system("pause");    return;}

这里写图片描述

这里写图片描述

(2)按字符读取文件

#define  _CRT_SECURE_NO_WARNINGS #include <stdlib.h>#include <string.h>#include <stdio.h>void main(){    int     i = 0;    FILE *fp = NULL;    char *filename2 = "c:/2.txt";     fp = fopen(filename2, "r+");//读写的方式,打开文件 如果文件不存在,则报错    if (fp == NULL)    {        printf("func fopen() err:%d \n");        return;    }    printf("打开成功\n");    while (!feof(fp))    {        char tempc = fgetc(fp);        printf("%c", tempc);    }    printf("\n读取成功\n");    if (fp != NULL)    {        fclose(fp);    }    printf("hello...\n");    system("pause");    return;}

这里写图片描述

(3)按行写入文件

#define  _CRT_SECURE_NO_WARNINGS #include <stdlib.h>#include <string.h>#include <stdio.h>void main(){    int     i = 0;    FILE *fp = NULL;    char *filename2 = "c:/22.txt";    char a[27] = "1sad3ddddsad4da";    fp = fopen(filename2, "w+");//读写的方式,打开文件 如果文件不存在,则自动新建一个    if (fp == NULL)    {        printf("func fopen() err:%d \n");        return;    }    printf("打开成功\n");    fputs(a, fp);    printf("写入成功\n");    fclose(fp);    printf("hello...\n");    system("pause");    return;}

这里写图片描述

这里写图片描述

(4)按行读取文件

#define  _CRT_SECURE_NO_WARNINGS #include <stdlib.h>#include <string.h>#include <stdio.h>void main(){    int     i = 0;    FILE *fp = NULL;    char *filename2 = "c:/22.txt";    char buf[1024];    fp = fopen(filename2, "r+");    if (fp == NULL)    {        printf("func fopen() err:%d \n");        return;    }    printf("打开成功\n");    while (!feof(fp))    {        char *p = fgets(buf, 1024, fp); //C 函数库会 一行一行的copy数据到buf指针所指的内存空间中并且变成C风格的字符串        if (p == NULL)        {            goto End;        }        printf("%s", buf);    }End:    if (fp != NULL)    {        fclose(fp);    }    printf("读取成功\n");    fclose(fp);    printf("hello...\n");    system("pause");    return;}

这里写图片描述

这里写图片描述

(5)按照块的方式写入文件

#define  _CRT_SECURE_NO_WARNINGS #include <stdlib.h>#include <string.h>#include <stdio.h>//直接把内存数据写入到文件中typedef struct Teacher{    char name[64];    int age;}Teacher;void main(){    int i = 0;    FILE *fp = NULL;    char *fileName = "c:/3.data";    Teacher tArray[3];    int  myN = 0;    for (i = 0; i < 3; i++)    {        sprintf(tArray[i].name, "%d%d%d", i + 1, i + 1, i + 1);        tArray[i].age = i + 31;    }    fp = fopen(fileName, "wb");    if (fp == NULL)    {        printf("建立文件失败\n");        return;    }    printf("建立文件成功\n");    for (i = 0; i < 3; i++)    {         // fwrite(_In_count_x_(_Size*_Count) const void * _Str, _In_ size_t _Size, _In_ size_t _Count, _Inout_ FILE * _File);        //函数参数        //_Str : 从内存块的开始        //_Size: 写多长        //_Count: 写多少次        //_File : 写入到文件指针所指向的文件中        //函数的返回值         myN = fwrite(&tArray[i], sizeof(Teacher), 1, fp);        //myN 用于判断有没有写满磁盘    }    printf("写入成功\n");    if (fp != NULL)    {        fclose(fp);    }    printf("hello...\n");    system("pause");    return;}

这里写图片描述

(6)按照块的方式读取文件

#define  _CRT_SECURE_NO_WARNINGS #include <stdlib.h>#include <string.h>#include <stdio.h>typedef struct Teacher{    char name[64];    int age;}Teacher;void main(){    int i = 0;    FILE *fp = NULL;    char *fileName = "c:/3.data";    Teacher tArray[3];    int  myN = 0;    fp = fopen(fileName, "r+b");    if (fp == NULL)    {        printf("建立文件失败\n");        return;    }    for (i = 0; i < 3; i++)    {        // fread(_Out_bytecap_x_(_ElementSize*_Count) void * _DstBuf, _In_ size_t _ElementSize, _In_ size_t _Count, _Inout_ FILE * _File);        myN = fread(&tArray[i], sizeof(Teacher), 1, fp);    }    for (i = 0; i < 3; i++)    {        printf("name:%s, age:%d \n", tArray[i].name, tArray[i].age);    }    if (fp != NULL)    {        fclose(fp);    }    printf("hello...\n");    system("pause");    return;}

这里写图片描述

2.配置文件读写案例

1.要求

  • 1). 配置文件读(根据key,读取value,有就打印出来)
  • 2). 配置文件写(输入key、value)
  • 3). 配置文件修改(输入key、value)
  • 4). 优化 ==> 接口、模块

2.实现步骤

  • 1).写一个头文件my.h(写接口)
  • 2).写一个源文件cfg.c(实现读写操作)
  • 3).写一个源文件test.c(用于测试代码)
  • 4).写一个配置文件mycfg.ini

3.头文件my.h代码

#ifndef __MY__#define __MY__#ifdef  __cplusplusextern "C" {#endif//获取配置项int GetCfgItem(char *pFileName /*in*/, char *pKey /*in*/, char * pValue/*in out*/, int * pValueLen /*out*/);//写配置项 int WriteCfgItem(char *pFileName /*in*/, char *pItemName /*in*/, char *pItemValue/*in*/, int itemValueLen /*in*/);#ifdef  __cplusplus}#endif#endif

4.源文件cfg.c代码

#define  _CRT_SECURE_NO_WARNINGS #include <stdlib.h>#include <string.h>#include <stdio.h>#define MaxLine 2048 //最大行数//获取配置项int GetCfgItem(char *pFileName /*in*/, char *pKey /*in*/, char * pValue/*in out*/, int * pValueLen /*out*/){    int     ret = 0;    FILE    *fp = NULL;    char    *pTmp = NULL, *pEnd = NULL, *pBegin = NULL;    char lineBuf[MaxLine];    fp = fopen(pFileName, "r");    if (fp == NULL)    {        ret = -1;        return ret;    }    while (!feof(fp))    {        memset(lineBuf, 0, sizeof(lineBuf));        //fgets(_Out_z_cap_(_MaxCount) char * _Buf, _In_ int _MaxCount, _Inout_ FILE * _File);        fgets(lineBuf, MaxLine, fp);        //printf("lineBuf:%s ",lineBuf );        pTmp = strchr(lineBuf, '=');         if (pTmp == NULL) //如果此行没有=号,跳下一行        {            continue;        }        pTmp = strstr(lineBuf, pKey);        if (pTmp == NULL) //判断key是不是在所在行        {            continue;        }        pTmp = pTmp + strlen(pKey); //mykey1 = myvalude1 ==> "= myvalude1"        //可能key与=号之间有空格,此时可以直接去找=号        pTmp = strchr(pTmp, '=');        if (pTmp == NULL) //在判断有没有=号        {            continue;        }        pTmp = pTmp + 1;        //获取value起点        while (1)         {            if (*pTmp == ' ')            {                pTmp ++ ;            }             else            {                pBegin = pTmp;                if (*pBegin == '\n')                {                    //没有配置value                    //printf("配置项:%s 没有配置value \n", pKey);                    goto End;                }                break;            }        }        //获取valude结束点        while (1)         {            if ((*pTmp == ' ' || *pTmp == '\n'))            {                break;            }            else             {                pTmp ++;            }        }        pEnd = pTmp;        //赋值,此时就去除了前后的空格        *pValueLen = pEnd-pBegin;        memcpy(pValue, pBegin, pEnd-pBegin);    }End:    if (fp == NULL)    {        fclose(fp);    }    return 0;}//写配置项 //实现流程//循环读每一行,检查key配置项是否存在 若存在修改对应value值//若不存在,在文件末尾 添加 "key = value"int WriteCfgItem(char *pFileName /*in*/, char *pKey /*in*/, char * pValue/*in*/, int ValueLen /*in*/){    int     rv = 0, iTag = 0, length = 0;    FILE    *fp = NULL;    char    lineBuf[MaxLine];    char    *pTmp = NULL, *pBegin = NULL, *pEnd = NULL;    char    filebuf[1024*8] = {0};    if (pFileName==NULL || pKey==NULL || pValue==NULL)     {        rv = -1;        printf("SetCfgItem() err. param err \n");        goto End;    }    //打开文件    fp = fopen(pFileName, "r+");    if (fp == NULL)    {        rv = -2;        printf("fopen() err. \n");    }    if (fp == NULL)    {        //如果文件不存在,则建一个文件(为了友好)        fp = fopen(pFileName, "w+t");        if (fp == NULL)        {            rv = -3;            printf("fopen() err. \n");            goto End;        }    }    fseek(fp, 0L, SEEK_END); //把文件指针从0位置开始,移动到文件末尾    //获取文件长度;    length = ftell(fp);    fseek(fp, 0L, SEEK_SET);    if (length > 1024*8)     {        rv = -3;        printf("文件超过1024*8, nunsupport");        goto End;    }    while (!feof(fp))    {        //读每一行        memset(lineBuf, 0, sizeof(lineBuf));        pTmp = fgets(lineBuf, MaxLine, fp);        if (pTmp == NULL)         {            break;        }        //key关键字是否在本行        pTmp = strstr(lineBuf, pKey);        if (pTmp == NULL) //key关键字不在本行, copy到filebuf中        {            strcat(filebuf, lineBuf);            continue;        }        else  //key关键字在本行中,替换旧的行,再copy到filebuf中         {            sprintf(lineBuf, "%s = %s\n", pKey, pValue);              strcat(filebuf, lineBuf);            //若存在key            iTag = 1;         }    }    //若key关键字,不存在追加    if (iTag == 0)     {        fprintf(fp, "%s = %s\n", pKey, pValue);    }    else //若key关键字,存在,则重新创建文件    {        if (fp != NULL)         {             fclose(fp);             fp = NULL; //避免野指针        }        fp = fopen(pFileName, "w+t");         if (fp == NULL)        {            rv = -4;            printf("fopen() err. \n");            goto End;        }        fputs(filebuf, fp);    }End:    if (fp != NULL)    {        fclose(fp);     }    return rv;}

5.源文件test.c代码

#define  _CRT_SECURE_NO_WARNINGS #include <stdlib.h>#include <string.h>#include <stdio.h>#include "my.h"#define CFGNAME "c:/mycfg.ini"void mymenu(){    printf("=============================\n");    printf("1 写配置文件\n");    printf("2 读配置文件\n");    printf("0 退出\n");    printf("=============================\n");}//读配置项int TGetCfg(){    int     ret = 0;    char    name[1024] = {0};    char    value1[1024] = { 0 };    int     vlen = 0;    printf("\n请键入key:");    scanf("%s", name);    ret = GetCfgItem(CFGNAME /*in*/, name /*in*/, value1/*in*/, &vlen);    if (ret != 0)    {        printf("func WriteCfgItem err:%d \n", ret);        return ret;    }    printf("value:%s \n", value1);}//写配置项 int TWriteCfg(){    int     ret = 0;    char name[1024] = {0};    char value1[1024] = {0};    printf("\n请键入key:");    scanf("%s", name);    printf("\n请键入value:");    scanf("%s", value1);    ret = WriteCfgItem(CFGNAME /*in*/, name /*in*/, value1/*in*/, strlen(value1) /*in*/);    if (ret != 0)    {        printf("func WriteCfgItem err:%d \n", ret);        return ret;    }    printf("你的输入是:%s = %s \n", name, value1);    return ret;}void main(){    int choice;    for (;;)    {        //显示一个菜单        mymenu();        scanf("%d", &choice);        switch (choice)        {                   case 1:                   TWriteCfg();//写配置项                break;            case 2:                 TGetCfg(); //读配置项                break;            case 0:                 exit(0);            default:;                exit(0);        }    }    printf("hello...\n");    system("pause");    return ;}

6.配置文件mycfg.ini

这里写图片描述

7.测试结果

这里写图片描述

这里写图片描述

原创粉丝点击