Skip to content

Commit 9361c90

Browse files
committed
task two: 1-create_file.c - status: new
1 parent 0084f8d commit 9361c90

File tree

3 files changed

+68
-0
lines changed

3 files changed

+68
-0
lines changed

0x15-file_io/1-create_file.c

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
#include "main.h"
2+
3+
/**
4+
* create_file - creates 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 create_file(const char *filename, char *text_content)
12+
{
13+
int fd_wr, fd, flags, perm, 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_CREAT | O_TRUNC | O_WRONLY;
30+
perm = S_IRUSR | S_IWUSR;
31+
32+
fd = open(filename, flags, perm);
33+
if (fd < 0)
34+
return (-1);
35+
36+
if (text_content != NULL)
37+
{
38+
fd_wr = write(fd, text_content, text_content_len);
39+
if (fd_wr < 0)
40+
return (-1);
41+
}
42+
43+
close(fd);
44+
return (1);
45+
}

0x15-file_io/1-main.c

Lines changed: 22 additions & 0 deletions
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 = create_file(av[1], av[2]);
20+
printf("-> %i)\n", res);
21+
return (0);
22+
}

0x15-file_io/main.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,5 +8,6 @@
88
#include <fcntl.h>
99

1010
ssize_t read_textfile(const char *, size_t);
11+
int create_file(const char *, char *);
1112

1213
#endif

0 commit comments

Comments
 (0)