在編程中,我們經常會遇到一些配置文件或初始化文件。這些文件通常后綴名為.ini或者.conf,可以直接用記事本打開。里面會存儲一些程序參數,在程序中直接讀取使用。例如,計算機與服務器通信,服務器的ip地址,段口號可以存儲於ini文件中。這樣如果我想換另外一台服務器時,直接將ini文件中的ip地址改變即可,程序源代碼不需要做任何修改。
本文將分享一段常用代碼,用於讀取配置文件中的信息。本文中的代碼為C語言編寫,在ubuntu 12.04 linux系統中調試沒有問題。具體操作如下:
1. 首先用記事本創建一個config.ini文件(文件名可以隨便取),並假設該文件是我們要讀取的配置文件。文件內容如下:
information1: 1234567890 information2: this is test information information3: `~!@#$%^&*()_+{}-[]\|:"/.,<>
假設我們讀取的初始化文件每一行都是 <屬性名稱>: <屬性值> 的格式。在上述例子中,文件共有三行,分別代表三個屬性的信息。
2. 然后就是我們的代碼文件了,如下(將以下代碼存在ReadFile.cpp中):
#include <string.h> #include <stdio.h> const size_t MAX_LEN = 128; typedef struct{ char firstline[MAX_LEN]; char secondline[MAX_LEN]; char thirdline[MAX_LEN]; } Data; void readfile(Data *d){ const char *FileName = "config.ini"; char LineBuf[MAX_LEN]={0}; FILE *configFile = fopen(FileName, "r"); memset(d,0,sizeof(Data)); while(NULL != fgets(LineBuf, sizeof(LineBuf), configFile)) { size_t bufLen = strlen(LineBuf); if('\r' == LineBuf[bufLen-1] || '\n' == LineBuf[bufLen-1]) { LineBuf[bufLen-1] = '\0'; } char *pos = strchr(LineBuf,':'); if(NULL != pos) { *pos = '\0'; pos++; if(0 == strcmp(LineBuf, "information1")) { for(; *pos == ' '; pos++){} strcpy(d->firstline, pos); } else if(0 == strcmp(LineBuf, "information2")) { for(; *pos == ' '; pos++){} strcpy(d->secondline, pos); } else if(0 == strcmp(LineBuf, "information3")) { for(; *pos == ' '; pos++){} strcpy(d->thirdline, pos); } else { printf("Failed to read information from the file."); break; } } }
fclose(configFile);
configFile = NULL; return; } int main(int argc, char *argv[]) { Data *d = new Data; readfile(d); printf("d->firstline is \"%s\"\n", d->firstline); printf("d->secondline is \"%s\"\n", d->secondline); printf("d->thirdline is \"%s\"\n", d->thirdline); delete d; return 0; }
其中,struct Data是用於存儲要讀取的信息的結構體,readfile函數也就是實現我們讀取功能的函數,其中的值均存在struct Data中。最后我們寫了一個簡單的main函數用來測試結果。需要注意的是,在struct Data中,我們設置了char數組長度,最大不超過128。因此如果要讀取的信息超過128字節可能會出錯。如果有需要讀取更長的話可以將MAX_LEN設置為一個更大的值。
3. 最后就是我們的調試結果了,在命令行中運行如下命令
$ g++ -o test.out ReadFile.cpp $ ./test.out
然后就是運行結果:
d->firstline is "1234567890" d->secondline is "this is test information" d->thirdline is "`!@#$%^&*()_+{}-[]\|:"/.,<>"
這種讀取文件的代碼應該非常常用,要掌握。