-
Notifications
You must be signed in to change notification settings - Fork 0
/
file_ops.c
124 lines (112 loc) · 2.45 KB
/
file_ops.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
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
#include "main.h"
int cant_open(char *file_path);
int proc_file_commands(char *file_path, int *exe_ret);
/**
* cant_open - If the file doesn't exist or lacks proper permissions, print
* a cant open error.
* @file_path: Path to the supposed file.
*
* Return: 127.
*/
int cant_open(char *file_path)
{
char *error, *hist_str;
int len;
hist_str = _itoa(hist);
if (!hist_str)
return (127);
len = _strlen(name) + _strlen(hist_str) + _strlen(file_path) + 16;
error = malloc(sizeof(char) * (len + 1));
if (!error)
{
free(hist_str);
return (127);
}
_strcpy(error, name);
_strcat(error, ": ");
_strcat(error, hist_str);
_strcat(error, ": Can't open ");
_strcat(error, file_path);
_strcat(error, "\n");
free(hist_str);
write(STDERR_FILENO, error, len);
free(error);
return (127);
}
/**
* proc_file_commands - Takes a file and attempts to run the commands stored
* within.
* @file_path: Path to the file.
* @exe_ret: Return value of the last executed command.
*
* Return: If file couldn't be opened - 127.
* If malloc fails - -1.
* Otherwise the return value of the last command ran.
*/
int proc_file_commands(char *file_path, int *exe_ret)
{
ssize_t file, b_read, i;
unsigned int line_size = 0;
unsigned int old_size = 120;
char *line, **args, **front;
char buffer[120];
int ret;
hist = 0;
file = open(file_path, O_RDONLY);
if (file == -1)
{
*exe_ret = cant_open(file_path);
return (*exe_ret);
}
line = malloc(sizeof(char) * old_size);
if (!line)
return (-1);
do {
b_read = read(file, buffer, 119);
if (b_read == 0 && line_size == 0)
return (*exe_ret);
buffer[b_read] = '\0';
line_size += b_read;
line = _realloc(line, old_size, line_size);
_strcat(line, buffer);
old_size = line_size;
} while (b_read);
for (i = 0; line[i] == '\n'; i++)
line[i] = ' ';
for (; i < line_size; i++)
{
if (line[i] == '\n')
{
line[i] = ';';
for (i += 1; i < line_size && line[i] == '\n'; i++)
line[i] = ' ';
}
}
variable_replacement(&line, exe_ret);
handle_line(&line, line_size);
args = _strtok(line, " ");
free(line);
if (!args)
return (0);
if (check_args(args) != 0)
{
*exe_ret = 2;
free_args(args, args);
return (*exe_ret);
}
front = args;
for (i = 0; args[i]; i++)
{
if (_strncmp(args[i], ";", 1) == 0)
{
free(args[i]);
args[i] = NULL;
ret = call_args(args, front, exe_ret);
args = &args[++i];
i = 0;
}
}
ret = call_args(args, front, exe_ret);
free(front);
return (ret);
}