-
Notifications
You must be signed in to change notification settings - Fork 124
/
Copy pathexercise01.c
59 lines (45 loc) · 965 Bytes
/
exercise01.c
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
// C Primer Plus
// Chapter 13 Exercise 1:
// Modify Listing 13.1 so that it solicits the user to enter the filename and
// reads the user’s response instead of using command-line arguments.
#include <stdio.h>
#include <stdlib.h>
#define SLEN 81
void get(char * string, int n);
int main(void)
{
int ch;
FILE * fp;
char filename[SLEN];
unsigned long chcount = 0;
printf("Enter a file name: ");
get(filename, SLEN);
if ((fp = fopen(filename, "r")) == NULL)
{
printf("Could not open file %s\n", filename);
exit(EXIT_FAILURE);
}
while ((ch = getc(fp)) != EOF)
{
putc(ch, stdout);
chcount++;
}
printf("File %s has %lu characters.\n", filename, chcount);
fclose(fp);
return 0;
}
void get(char * string, int n)
{
// wrapper for fgets - read from stdin and replace
// first newline with null character
fgets(string, n, stdin);
while (*string != '\0')
{
if (*string == '\n')
{
*string = '\0';
break;
}
string++;
}
}