|
Generated by diff2html.pl © Yves Bailly, MandrakeSoft S.A. 2001, Ryohei Morita 2007 diff2html.pl is licensed under the GNU GPL. |
../02-1/02-1-OpenFile-NotSoGood.c | 02-2-OpenFile-Full.c | |||
---|---|---|---|---|
33 lines 805 bytes Last modified : Fri Nov 25 03:00:47 2011 |
46 lines 1231 bytes Last modified : Fri Nov 25 03:00:46 2011 |
|||
1 | // Keisanki Joron 2 (Introduction to Computing II) | 1 | // Keisanki Joron 2 (Introduction to Computing II) | |
2 | // Dept. of Engineering Systems, University of Tsukuba | 2 | // Dept. of Engineering Systems, University of Tsukuba | |
3 | // [UTF-8 / Unix] | 3 | // [UTF-8 / Unix] | |
4 | // 計算機序論2・実習 (筑波大学工学システム学類) | 4 | // 計算機序論2・実習 (筑波大学工学システム学類) | |
5 | 5 | |||
6 | // 2011/11/22a kameda[at]iit.tsukuba.ac.jp | 6 | // 2011/11/22a kameda[at]iit.tsukuba.ac.jp | |
7 | // 02.1. ファイルのぞんざいな開き方 | 7 | // 02.2. ファイルの上品な開き方 | |
8 | 8 | |||
9 | #include <stdio.h> | 9 | #include <stdio.h> | |
10 | 10 | |||
11 | int main(int argc, char *argv[]){ | 11 | int main(int argc, char *argv[]){ | |
12 | FILE *filetoopen; | 12 | FILE *filetoopen = NULL; // A pointer to FILE structure | |
13 | 13 | |||
14 | // Show number of options at command line | 14 | // Show number of options at command line | |
15 | printf("Number of Options : %d\n", argc); | 15 | printf("Number of Options : %d\n", argc); | |
16 | 16 | |||
17 | // We need at least one option for a file name to open | |||
18 | if (argc <= 1) { // What happens if you put other figure here? | |||
19 | printf("Error: You need to specify a file to open.\n"); | |||
20 | return 1; | |||
21 | } | |||
22 | ||||
17 | // Try to open it | 23 | // Try to open it | |
18 | printf("Let's open \"%s\"! \n", argv[1]); | 24 | printf("Let's open \"%s\"! \n", argv[1]); | |
19 | filetoopen = fopen(argv[1], "r"); | 25 | filetoopen = fopen(argv[1], "r"); | |
26 | if (filetoopen == NULL) { | |||
27 | printf("Error: Failed to open/read \"%s\".\n", argv[1]); | |||
28 | return 2; | |||
29 | } | |||
20 | printf("Ready to read \"%s\"\n", argv[1]); | 30 | printf("Ready to read \"%s\"\n", argv[1]); | |
21 | 31 | |||
22 | // Do something to get data from the file ... | 32 | // Do something to get data from the file ... | |
23 | 33 | |||
24 | // And close it | 34 | // And close it | |
25 | fclose(filetoopen); | 35 | if (fclose(filetoopen) != 0) { | |
36 | printf("Error: Failed to close \"%s\".\n", argv[1]); | |||
37 | return 3; | |||
38 | } | |||
26 | printf("File %s is now closed.\n", argv[1]); | 39 | printf("File %s is now closed.\n", argv[1]); | |
27 | 40 | |||
28 | // Do other things ... | 41 | // Do other things ... | |
29 | 42 | |||
30 | printf("All set. Bye!\n"); | 43 | printf("All set. Bye!\n"); | |
31 | return 0; | 44 | return 0; | |
32 | } | 45 | } | |
33 | 46 |