- 論壇徽章:
- 0
|
如下代碼中,主要目的是是從wgetrc配置文件中讀取一行配置,其中定義了一個幻數(shù) int bufsize = 81;
通過fgets()從文件中讀取一行數(shù)據(jù),這里對一行的數(shù)據(jù)做了個假設(shè),假設(shè)大多數(shù)數(shù)據(jù)不超過81個字節(jié),
然后在實際讀取時,如果超過一行數(shù)據(jù)超過81字節(jié),即讀取了80個字節(jié)的數(shù)據(jù)后,還沒有讀到'\n',那么就realloc(xrealloc())一倍的內(nèi)存空間來重新繼續(xù)讀取數(shù)據(jù),
感覺似乎是為了節(jié)約內(nèi)存,而這樣的的情況下,就多了一次系統(tǒng)調(diào)用,值得么?或者是我理解錯誤了?- char *
- read_whole_line (FILE *fp)
- {
- int length = 0;
- int bufsize = 81;
- char *line = xmalloc (bufsize); // malloc()帶了錯誤檢測,以下類似程序雷同
- // char *fgets(char *s, int size, FILE *stream);
- while (fgets (line + length, bufsize - length, fp))
- {
- length += strlen (line + length);
- assert (length > 0);
- if (line[length - 1] == '\n')
- break;
- /* fgets() guarantees to read the whole line, or to use up the
- space we've given it. We can double the buffer
- unconditionally. */
- bufsize <<= 1;
- line = xrealloc (line, bufsize);
- }
- if (length == 0 || ferror (fp))
- {
- xfree (line); // #define xfree free
- return NULL;
- }
- if (length + 1 < bufsize)
- /* Relieve the memory from our exponential greediness. We say
- `length + 1' because the terminating \0 is not included in
- LENGTH. We don't need to zero-terminate the string ourselves,
- though, because fgets() does that. */
- line = xrealloc (line, length + 1);
- return line;
- }
復(fù)制代碼 |
|