This commit is contained in:
2026-03-02 02:12:28 +01:00
parent 88b0c96605
commit 77cd47526c
7 changed files with 572 additions and 0 deletions
+143
View File
@@ -0,0 +1,143 @@
#include "village.h"
#include <stddef.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <stdio.h>
char *get_quote(const struct villager *village, unsigned int population, char *name){
if (!village || population <= 0) return NULL;
unsigned int index = 0;
while(index < population){
if(!strcmp(village[index].name, name))
return village[index].favorite_quote;
index ++;
}
//if(index == population) return NULL;
return NULL;
}
int list_quotes(const char *filename, const struct villager *village, unsigned int population){
if(!filename || !village) return -1;
FILE *file = fopen(filename, "w");
if(!file) return -2;
unsigned int index = 0;
while(index < population){
fprintf(file, "%s\n", village[index].favorite_quote);
index ++;
}
fclose(file);
return 0;
}
char *second_longest_quote(const char *filename){
if(!filename) return NULL;
FILE *file = fopen(filename, "r");
if(!file)return NULL;
//utiliser getline
//utiliser strcmp() //comparaison entre deux str
//char *max_line = malloc(sizeof(char));
//char *second_line = malloc(sizeof(char));
char *max_line = NULL;
char *sc_line = NULL;
char *tmp_line = NULL;
size_t index = 0;
ssize_t len_max = 0;
ssize_t len_sec = 0;
ssize_t len_tmp = 0;
//char *c = fgets(char *restrict s, int n, FILE *restrict stream);
//lecture fichier
while((len_tmp = getline(&tmp_line, &index, file)) != -1){ // si la ligne est plus grande que max_line
if(len_tmp > len_max){
len_sec = len_max;
len_max = len_tmp;
free(sc_line);
sc_line = max_line;
max_line = strdup(tmp_line);
}
else if (len_tmp > len_sec){
len_sec = len_tmp;
free(sc_line);
sc_line = strdup(tmp_line);
}
}
free(tmp_line);
free(max_line);
fclose(file);
return sc_line;
}
/*
int main(void)
{
struct villager village[2] = {
{
.name = "Tom Nook",
.age = 99,
.job = SELLER,
.favorite_quote = "It's 42 bells",
},
{
.name = "Marie",
.age = 23,
.job = WORKER,
.favorite_quote = "It's so expensive!",
},
};
unsigned int population = 2;
char *quote = get_quote(village, population, "Tom Nook");
printf("- %s\n", quote);
quote = get_quote(village, population, "Marie");
printf("- %s\n", quote);
quote = get_quote(village, population, "TC");
printf("%p\n", quote);
int err = list_quotes("/tmp/list_quotes", village, population);
printf("%d\n", err);
err = list_quotes(NULL, village, population);
printf("%d\n", err);
printf("the last\n");
quote = second_longest_quote("/tmp/list_quotes");
printf("%s\n", quote);
free(quote);
quote = second_longest_quote("/");
printf("%p\n", quote);
free(quote);
}*/