Utilisation de static char * dans un cas precis
Bonsoir,
Je cherche a faire un petit programme qui fait un read sur l'entrée standard, récupère ce qu'on écrit dans un char *, jusqu'a tomber sur un '/n' (lorsqu'on appuie sur la touche entrée), et renvoie 0.
Seulement je veux faire quelque chose de dynamique, qui pourrait fonctionner avec un buffer d'une taille plus petite que la taille des arguments qu'on lui donne, en faisant plusieurs read, et pour se faire j'ai besoin de déclarer des static char*, et ca, je ne maitrise pas du tout...
Voici donc un code qui illustre comment je vois les choses (qui ne compile pas), merci pour vos explications !
.get_next_line.h
.get_next_line.c
.main.c
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| #ifndef __GET_NEXT_LINE_H__
# define __GET_NEXT_LINE_H__
#define BUFF_SIZE 1
typedef struct s_test
{
static char *result;
} t_test;
int get_next_line(const int fd, t_test *ptr);
void my_putstr(char *str);
int my_strlen(char *str);
#endif /*__MY_GET_NEXT_LINE__ */ |
Code:
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
| #include <stdlib.h>
#include <unistd.h>
#include "get_next_line.h"
void my_malloc(static char *(*result), int debut, char *buffer, int fin)
{
int i;
i = debut;
while ((buffer[debut] != '\n') && (debut < fin))
debut++;
if (buffer[debut] == '\n')
*result = malloc(((debut - i) + 1) * sizeof(*(*result)));
else
*result = malloc((debut - i) * sizeof(*(*result)));
}
int get_next_line(const int fd, t_test *ptr)
{
char buffer[BUFF_SIZE];
static int debut = 0;
static int j = 0;
static int fin;
if (debut == 0 || debut == fin)
fin = read(fd, buffer, BUFF_SIZE);
my_malloc(&(ptr->result), debut, buffer, fin);
while ((buffer[debut] != '\n') && (debut < fin))
{
ptr->result[j] = buffer[debut];
j++;
debut++;
}
if (buffer[debut] == '\n')
{
ptr->result[j] = '\0';
return (0);
}
else
return (-1);
} |
Code:
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
| #include <stdio.h>
#include <fcntl.h>
#include <stdlib.h>
#include "get_next_line.h"
int my_strlen(char *str)
{
int i;
i = 0;
while (str[i])
i++;
return (i);
}
void my_putstr(char *str)
{
write(1,str,my_strlen(str));
}
int main()
{
t_test args;
while (get_next_line(0, &args) != 0)
get_next_line(0, &args);
return (0);
} |