-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathhandle_comment.c
More file actions
50 lines (43 loc) · 1.25 KB
/
Copy pathhandle_comment.c
File metadata and controls
50 lines (43 loc) · 1.25 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
#include "shell.h"
/**
* remove_comments - remove comments from a command before parsing
* @command: the input command
*
* Return: the modified command if # are found
* or the command itself if no comments are found.
*
*/
char *remove_comments(char *command)
{
size_t offset;
const char *position;
char *modified_command;
/* Find the first occurrence of # */
position = _strchr(command, '#');
/* If no # is found, return the command */
if (position == NULL)
return (command);
/* Calc. the offset, i.e., the position of the # character in the string */
offset = position - command;
/* Check if # is at the start of the string or follows whitespace */
if (offset == 0 || (offset > 0 && isspace(command[offset - 1])))
{
/* Allocate a new string to store the modified command */
modified_command = malloc(offset + 1);
if (modified_command == NULL)
{
fprintf(stderr, "Memory allocation error\n");
safefree(modified_command);
exit(EXIT_FAILURE);
}
/* Copy the relevant portion of the command into the new string */
_strncpy(modified_command, command, offset);
modified_command[offset] = '\0';
return (modified_command);
}
else
{
/* If # is not at start or following whitespace, return the command */
return (command);
}
}