C語言文件操作-文件讀寫

學習了文件的一些操作,使用文件操作來實現簡易的文件的讀取和寫入功能。

功能:寫入名稱和對應的屬性,根據名稱查詢出對應的屬性

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);
		//printf("%s", linebuf);

		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;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章