-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.c
More file actions
140 lines (107 loc) · 2.29 KB
/
main.c
File metadata and controls
140 lines (107 loc) · 2.29 KB
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#ifdef _WIN32
#include <windows.h>
#else
#include <dirent.h>
#endif
const size_t MAX_BUFFER_SIZE = 256;
const size_t MAX_FILENAME_SIZE = 32;
const char PAGE_FORMAT[] = "%d.txt";
int find_last_page()
{
int last_page = 0;
#ifdef _WIN32
WIN32_FIND_DATA findFileData;
HANDLE hFind = FindFirstFile("*.txt", &findFileData);
if (hFind == INVALID_HANDLE_VALUE)
{
return 0; // no file found
}
do
{
int num;
if (sscanf(findFileData.cFileName, PAGE_FORMAT, &num) == 1)
{
if (num > last_page)
last_page = num;
}
} while (FindNextFile(hFind, &findFileData));
FindClose(hFind);
#else
DIR *d = opendir(".");
struct dirent *entry;
while ((entry = readdir(d)) != NULL)
{
int num;
if (sscanf(entry->d_name, PAGE_FORMAT, &num) == 1)
{
if (num > last_page)
last_page = num;
}
}
closedir(d);
#endif
return last_page;
}
void create_new_page(int last_page)
{
char filename[MAX_FILENAME_SIZE];
sprintf(filename, PAGE_FORMAT, last_page + 1);
FILE *f = fopen(filename, "w");
fclose(f);
}
void read_page(int page_number)
{
char filename[MAX_FILENAME_SIZE];
sprintf(filename, PAGE_FORMAT, page_number);
FILE *f = fopen(filename, "r");
int c;
while ((c = fgetc(f)) != EOF)
{
putchar(c);
}
fclose(f);
}
void write_page(int page_number)
{
char filename[MAX_FILENAME_SIZE];
sprintf(filename, PAGE_FORMAT, page_number);
FILE *f = fopen(filename, "a");
printf("#\n");
char buffer[MAX_BUFFER_SIZE];
fgets(buffer, sizeof(buffer), stdin);
fprintf(f, "%s\n", buffer);
fclose(f);
}
int main(int argc, char **argv)
{
int last_page = find_last_page();
for (int i = 1; i < argc; i++)
{
if (strcmp(argv[i], "-r") == 0 || strcmp(argv[i], "--read") == 0)
{
int input;
if (i + 1 >= argc)
{
input = last_page;
}
else
{
input = atoi(argv[i + 1]);
}
int page = input > last_page ? last_page : input;
read_page(page);
return EXIT_SUCCESS;
}
if (strcmp(argv[i], "-n") == 0 || strcmp(argv[i], "--new") == 0)
{
create_new_page(last_page);
return EXIT_SUCCESS;
}
}
write_page(last_page);
return EXIT_SUCCESS;
}