Skip to content

Commit 4a8b86c

Browse files
committed
task three: 2-append_text_to_file.c - status: new
1 parent 9361c90 commit 4a8b86c

File tree

3 files changed

+67
-0
lines changed

3 files changed

+67
-0
lines changed

0x15-file_io/2-append_text_to_file.c

+44
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
#include "main.h"
2+
3+
/**
4+
* append_text_to_file - appends text at the end of a file.
5+
*
6+
* @filename: file name.
7+
* @text_content: text to be add into the file.
8+
*
9+
* Return: (1) on success, (-1) on failure.
10+
*/
11+
int append_text_to_file(const char *filename, char *text_content)
12+
{
13+
int fd_wr, fd, flags, text_content_len = 0;
14+
15+
if (filename == NULL)
16+
return (-1);
17+
18+
if (text_content != NULL)
19+
{
20+
while (*text_content != '\0')
21+
{
22+
text_content_len++;
23+
text_content++;
24+
}
25+
26+
text_content = text_content - text_content_len;
27+
}
28+
29+
flags = O_WRONLY | O_APPEND;
30+
31+
fd = open(filename, flags);
32+
if (fd < 0)
33+
return (-1);
34+
35+
if (text_content != NULL)
36+
{
37+
fd_wr = write(fd, text_content, text_content_len);
38+
if (fd_wr < 0)
39+
return (-1);
40+
}
41+
42+
close(fd);
43+
return (1);
44+
}

0x15-file_io/2-main.c

+22
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
#include <stdio.h>
2+
#include <stdlib.h>
3+
#include "main.h"
4+
5+
/**
6+
* main - check the code
7+
*
8+
* Return: Always 0.
9+
*/
10+
int main(int ac, char **av)
11+
{
12+
int res;
13+
14+
if (ac != 3)
15+
{
16+
dprintf(2, "Usage: %s filename text\n", av[0]);
17+
exit(1);
18+
}
19+
res = append_text_to_file(av[1], av[2]);
20+
printf("-> %i)\n", res);
21+
return (0);
22+
}

0x15-file_io/main.h

+1
Original file line numberDiff line numberDiff line change
@@ -9,5 +9,6 @@
99

1010
ssize_t read_textfile(const char *, size_t);
1111
int create_file(const char *, char *);
12+
int append_text_to_file(const char *, char *);
1213

1314
#endif

0 commit comments

Comments
 (0)