文章目录
- 一、文件中常用的函数
- fopen()
- fputs()
- fflush()
- fclose()
- 二、使用实例
- 1.读取文件
- 2.写入文件
- 3.main()
- 总结
一、文件中常用的函数
fopen()
打开文件
fopen(const char* filename, const char* mode)
filename:文件名
mode:打开方式,控制读写权限,数据形式为字符串,一般为:
r | 只读 |
---|---|
w | 只写 |
r+ | 读写 |
w+ | 更新,写入 |
a | 保留之前的内容写入 |
fputs()
向输入流stream写入数据
fputs(const char* str, FILE *stream)
str: 存储数据的字符数组
fflush()
刷新缓冲区,即将缓冲区的数据立刻写入文件,同时清空缓冲区。
fflush(FILE *stream)
fclose()
关闭一个文件流,释放指针和有关的缓冲区。
fflush(FILE *stream)
二、使用实例
文件名为config.txt,内容如下
name:张三
sex:男
age:60
income:8000
1.读取文件
代码如下:
int GetConfigFromFile(char *filename)
{FILE *f = fopen(filename, "r");char buffer[1024];char *b;char *p;char *stop;char *last;if(NULL == f){printf("Failed to open %s\n", filename);return 0;}printf("Open file %s successfully\n", filename);while(NULL != (b = fgets(buffer, 1024, f))){if(b[0] == '#') continue;p = strtok_r(b, ":", &last);if(p != NULL){char* val = strtok_r(last, "\n", &last);if(NULL ==val)continue;else{while((*val == ' ')||(*val == '\t')){val++;}if(strstr(p, "name")) strncpy(m_name, val, sizeof(m_name) - 1);else if(strstr(p, "sex")) strncpy(m_sex, val, sizeof(m_sex) - 1);else if(strstr(p, "age"))m_age = strtol(val, &stop, 0); else if(strstr(p, "income")) m_income = strtol(val, &stop, 0);elseprintf("Unknown message: %s\n", p);}}}fclose(f);return 1;
}
运行结果如下:
2.写入文件
代码如下:
int WriteConfigFromFile(char *filename)
{FILE *f = fopen(filename, "w+");if(NULL == f){printf("file is not exist\n");return 0;}printf("Open file successfully\n");char buffer[1024] = {0};snprintf(buffer, 1024, "name:%s\n", m_name);fputs(buffer, f);memset(buffer, 0, 1024);snprintf(buffer, 1024, "age:%d\n", m_age);fputs(buffer, f);memset(buffer, 0, 1024);snprintf(buffer, 1024, "sex:%s\n", m_sex);fputs(buffer, f);memset(buffer, 0, 1024);snprintf(buffer, 1024, "income:%d\n", m_income);fputs(buffer, f);fflush(f);fclose(f);return 1;
}
运行结果如下:
3.main()
int main()
{char filename[32] = {0};strncpy(filename, "config.txt", 32);if(0==GetConfigFromFile(filename)){printf("Read file faily\n");return 0;}else{printf("Read file successfully\n");printf("my name is %s, age is %d, sex is %s, income is %d\n", m_name, m_age, m_sex, m_income);}strncpy(m_name, "李四", sizeof(m_name) - 1);strncpy(m_sex, "女", sizeof(m_sex) - 1);m_age = 59;m_income = 20;if(0 == WriteConfigFromFile(filename)){printf("Write file faily\n");return 0;}printf("Write file successfully\n");return 0;
}
总结
文件读写是基本操作,我是在Linux下编译,若在windows的集成环境下会有所不同,大家最关键的是要掌握和理解文件的基本函数。