- 论坛徽章:
- 0
|
修改后的代码
- /*reference:The Art and Science of C*/
- int readLine(FILE * infile, char ** line) {
- char * tmp, *test;
- int c, n = 0, size = BUFSIZE;
- if (*line) {
- free(*line);
- }
- *line = (char *) malloc(size + 1);
- if (!*line) {
- return 0;
- }
- while ((c = fgetc(infile)) != '\n' && c != EOF) {
- if (n == size) {
- size *= 2;
- //tmp = (char *) malloc(size + 1);
- tmp = (char *) realloc(*line, size + 1);
-
- if (!tmp) {
- //line = 0;
- //return 0;
- return n;
- }
-
- //strncpy(tmp, *line, n);
- //free(*line);
- test = *line;
- *line = tmp;
- }
- *(*line + n) = c;
- n++;
- }
- if (n == 0 && c == EOF) {
- *line = NULL;
- free(*line);
- return 0;
- }
-
- *(*line + n)= '\0';
- tmp = 0;
- return n;
- }
复制代码 |
|