欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 财经 > 金融 > C高级编程 第七天(文件读写练习)

C高级编程 第七天(文件读写练习)

2026/3/10 7:16:22 来源:https://blog.csdn.net/m0_53349772/article/details/141507831  浏览:    关键词:C高级编程 第七天(文件读写练习)

目录

有一个文件如下,包括key:value

 ①根据字符串判断是否是有效行

②计算文件有效行数

③解析文件

④根据key获取对应的value

⑤释放内存


有一个文件如下,包括key:value

 ①根据字符串判断是否是有效行

该字符串只有换行符或者不包含冒号就不算做一行;该字符串包含":"则为有效行数

int isInvalidLine(char* arr)
{if (arr[0] == '\n' || strchr(arr, ':') == NULL)//若此行只有换行符 或者 不包含冒号 就不算做一行{return 0;}return 1;
}

②计算文件有效行数

按行读取文件,若该行是有效行,则行数加一

int getLines(const char* Path)
{FILE* file = fopen(Path, "r");char arr[64] = { 0 };int line = 0;//记录行数if (file != NULL){while (fgets(arr, 1024, file) != NULL)	//按行读取{if (1 == isInvalidLine(arr))	//如果此行有效,则行数加一{line++;}}}return line;
}

③解析文件

将文件中的内容存放到结构体中

int parseFile(const char* filepath, int lines, struct ConfigInfo** configInfo)
{struct ConfigInfo* config = (struct ConfigInfo*)malloc(sizeof(struct ConfigInfo) * lines);FILE* file = fopen(filepath, "r");if (NULL != file){int index = 0;char buff[1024] = { 0 };//将每行读取的数据放入其中while (NULL != fgets(buff, 64, file)){if (1== isInvalidLine(buff)){//清空结构体memset(configInfo[index]->key, 0, 64);memset(configInfo[index]->value, 0, 64);char* arr = strchr(buff, ':');strncpy(configInfo[index]->key, buff, arr - buff);strncpy(configInfo[index]->value, arr+1, strlen(arr+1)-1);//-1是为了不要文件中的换行符printf("key是%s\n", configInfo[index]->key);printf("value是%s\n", configInfo[index]->value);index++;}}memset(buff, 0, 1024);}*configInfo = config;
}

④根据key获取对应的value

char* getValueByKey(char* key, ConfigInfo* configInfo, int lines)
{for (int i = 0; i < sizeof(configInfo) / sizeof(struct ConfigInfo); i++){if (key == configInfo[i].key){return configInfo[i].value;}}return nullptr;
}

⑤释放内存

void freeSpace(ConfigInfo* configInfo)
{if (NULL == configInfo){return;}free(configInfo);configInfo = nullptr;
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词