File: rogers_example05e.c

package info (click to toggle)
lg-issue39 2-4
  • links: PTS
  • area: main
  • in suites: woody
  • size: 1,408 kB
  • ctags: 145
  • sloc: ansic: 207; perl: 72; makefile: 37; sh: 4
file content (61 lines) | stat: -rw-r--r-- 1,346 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
#include <stdio.h>
#include <stdlib.h>

/*
	This program is written to demonstrate the <stdlib.h> library.
	This program will demonstrate memory allocation using calloc and realloc.
	Written by James M. Rogers
	21 March 1999
	Released to the Public Domain on this date.
*/

/*
	Read in lines from a file, reallocating memory as needed, then freeing when done.
*/

#define SIZE 1024

main(int argv, char *argc[]){

    char *file;
    char line[SIZE];
    FILE *stream;
    unsigned int mem_size, file_size, line_size;

    mem_size=SIZE;
    file_size=0;

    if((file=calloc(1,SIZE))==(char *)NULL){
	printf("Cannot allocate memory.\n");
	exit (1);
    }

    if((stream=fopen(argc[1], "r")) == (FILE *)NULL){
	printf("Cannot open file.");
	exit (1);
    }

    while(fgets(line, SIZE+1, stream) != (char *)NULL) { 
        printf("%s",line);
	line_size=strlen(line);
        file_size += line_size;
        while(file_size>mem_size) {
	    mem_size += SIZE;
	    if ((file=realloc(file, mem_size)) == (char *)NULL){
		printf("Cannot allocate memory.\n");
                free(file);
		fclose(stream);
		exit (1);
	    }
        }
        strcat(file,line);
	printf("allocated memory:%d \t file size:%d \t size of line:%d\n", mem_size, file_size, line_size);
	 
    }

    printf("%s",file);

    fclose(stream);
    free(file);
    exit (0);
}