int get_key_value(char* path, char* key_str, int* val) { FILE *fp; if((fp = fopen(path, "r+")) == NULL) { perror("open"); return -1; } long file_len; fseek(fp, 0, SEEK_END); // 將文件指針移動到文件結尾,成功返回0,不成功返回-1 file_len = ftell(fp); // 求出當前文件指針距離文件開始的字節數 fseek(fp, 0, SEEK_SET); // 再定位指針到文件頭 char *str_buf = (char *)malloc(file_len + 1); while(fgets(str_buf, file_len, fp)) //循環讀取每一行內容,直到文件結束 { if(strstr(str_buf, key_str) != NULL) { int index= strlen(key_str); *val = atoi(&str_buf[index+1]);
printf("value = %d\n", *val); free(str_buf); fclose(fp); return 1; } } free(str_buf); fclose(fp); return -2; }
文件內容 test.txt
hello
ID=234
SDFAOW
TEMP=988
調用
int val = 0;
get_key_value("test.txt", "ID", &val);
運行結果
value = 234