C
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <string.h>
4 #include <unistd.h>
5 #include <sys/types.h>
6 #include <sys/stat.h>
7
8 int main(int argc, char **argv) {
9 struct stat filestat;
10 FILE *f;
11 char *filebuf = NULL;
12 char *buf_start;
13 char *delimiter = " \t\n\r\f\v";
14 char *s;
15
16 if(argc != 2) {
17 fprintf(stderr, "Usage: %s filename\n", argv[0]);
18 return EXIT_FAILURE;
19 }
20 if(! (f = fopen(argv[1], "r"))) goto ERROR;
21 if(stat(argv[1], &filestat) == -1) goto ERROR;
22 if(! (filebuf = (char *)calloc(filestat.st_size + 1, sizeof(char)))) goto ERROR;
23 buf_start = filebuf;
24 fread(filebuf, sizeof(char), filestat.st_size, f);
25 if(ferror(f)) goto ERROR;
26 if(fclose(f) == EOF) goto ERROR;
27 while(s = strsep(&filebuf, delimiter)) {
28 if(strlen(s) > 0) {
29 printf("%s\n", s);
30 }
31 }
32 free(buf_start);
33 return EXIT_SUCCESS;
34
35 ERROR:
36 if(filebuf) free(filebuf);
37 perror("");
38 return EXIT_FAILURE;
39 }
おまけ C (GNU Style)
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <string.h>
4 #include <unistd.h>
5 #include <sys/types.h>
6 #include <sys/stat.h>
7
8 int
9 main (argc, argv)
10 int argc;
11 char **argv;
12 {
13 struct stat filestat;
14 FILE *f;
15 char *filebuf = NULL;
16 char *buf_start;
17 char *delimiter = " \t\n\r\f\v";
18 char *s;
19
20 if (argc != 2)
21 {
22 fprintf(stderr, "Usage: %s filename\n", argv[0]);
23 return EXIT_FAILURE;
24 }
25 f = fopen (argv[1], "r");
26 if (! f)
27 {
28 goto ERROR;
29 }
30 if (stat(argv[1], &filestat) == -1)
31 {
32 goto ERROR;
33 }
34
35 filebuf = (char *)calloc (filestat.st_size + 1, sizeof (char));
36 if (! filebuf)
37 {
38 goto ERROR;
39 }
40
41 buf_start = filebuf;
42 fread (filebuf, sizeof (char), filestat.st_size, f);
43 if (ferror (f))
44 {
45 goto ERROR;
46 }
47 if (fclose (f) == EOF)
48 {
49 goto ERROR;
50 }
51 while (s = strsep (&filebuf, delimiter))
52 {
53 if (strlen(s) > 0)
54 {
55 printf ("%s\n", s);
56 }
57 }
58 free (buf_start);
59 return EXIT_SUCCESS;
60
61 ERROR:
62 if (filebuf)
63 {
64 free (filebuf);
65 }
66 perror ("");
67 return EXIT_FAILURE;
68 }