学习了文件操作的一些内容后,应用一下,做一个简易的文件读写功能的小程序
1.读取文件
int file_read(char *name){
char linebuf[1024];//文件的行值
char *check;//测试有没有 1.“=” ;2.对应名称
file = fopen(filename, "r");
if (file == NULL){
return 0; //没有内容
}
while (!feof(file)){
memset(linebuf, 0, sizeof(linebuf));
fgets(linebuf, 1024, file);
check=strchr(linebuf, '=');//没有=
if (check == NULL){
continue;
}
check = strstr(linebuf, name);
if (check == NULL)//没有对应名称
{
continue;
}
check = strstr(check, "=");
check += 1;
printf("value:%s", check);
}
fclose(file);
return 1;
}
2.写内容
int file_write(char*name, char*value){
file = fopen(filename, "a+");
fprintf(file, "%s=%s\n", name, value);
fclose(file);
return 1;
}
3.
int fun_read(){
printf("输入读取的名称:");
char name[64];
scanf("%s", name);
file_read(name);
return 1;
}
void main()
{
char select=-1;
printf("读写文件");
printf("%d",(char)select);
while (select != 0){
printf("\n\n1.写入数据\n2.读取数据\n0.退出\n");
do{
printf("输入操作序号:");
scanf("%d", &select);
} while ((int)select<48||(int)select>50);
switch (select)
{
case 1:fun_write(); break;
case 2:fun_read(); break;
default:
break;
}
}
return;
}