-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnano.c
61 lines (50 loc) · 1.24 KB
/
nano.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
60
61
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
/*
Simulates the behavior of the 'nano' command in Linux
nano file.txt
If the file does not exist, it creates a new empty file mode append
if found read and append it for write
*/
int main(int argc, char *argv[])
{
if (argc < 2)
{
printf("Usage: %s file\n", argv[0]);
return 1;
}
char buffer[1024];
const char *file = argv[1];
FILE *fptr = fopen(file, "a+");
printf("Welcome to nano \n");
printf("if you want exit print exit\n\n");
// Read and print existing content
rewind(fptr);
while (fgets(buffer, sizeof(buffer), fptr) != NULL)
{
printf("%s", buffer);
}
// write a new content
while (true)
{
fgets(buffer, sizeof(buffer), stdin);
if (buffer[strlen(buffer) - 1] == '\n')
{
buffer[strlen(buffer) - 1] = '\0';
}
else
{
int c;
while ((c = getchar()) != '\n' && c != EOF) ;
}
if (buffer[0] == '\0')
continue;
if (strcmp(buffer, "exit") == 0)
break;
fputs(buffer, fptr);
fputs("\n",fptr);
}
fclose(fptr);
return 0;
}