Hello i have a problem when i try to read conf file (line by line)
this is my code :
bool EndWith(const char* haystack, const char* needle)
{
bool rv = 0;
if (haystack && needle)
{
size_t needle_size = strlen(needle);
const char* act = haystack;
while (NULL != (act = strstr(act, needle)))
{
if (*(act + needle_size) == '\0')
{
rv = 1;
break;
}
act += needle_size;
}
}
return rv;
}
FILE *file2 = fopen ("config.conf", "r");
const size_t line_size = 300;
char* line = malloc(line_size);
while (fgets(line, line_size, file2) != NULL) {
puts(line);
if(EndWith(line, "toto")) {
puts("yes");
}
}
and my conf file :
vm.user_reserve_kbytes = 131072 toto
vm.vfs_cache_pressure = 100 toto
vm.zone_reclaim_mode = 0 toto
My code return 2 "Yes" but if my conf file, if i add a line feed in first line i read my 3 lines and my code return 3 "Yes" Why ?
i want to return 3 "Yes" without need to add a line feed in line0 of my conf file
bug retrurn :
vm.user_reserve_kbytes = 131072 toto
yes
vm.vfs_cache_pressure = 100 toto
yes
vm.zone_reclaim_mode = 0 toto
correct return (with add a line feed)
yes
vm.user_reserve_kbytes = 131072 toto
yes
vm.vfs_cache_pressure = 100 toto
yes
vm.zone_reclaim_mode = 0 toto
i tested solution Filip Kočica (thanks for your help) but i have same problem :
the code:
bool EndWith(const char* haystack, const char* needle)
{
if (haystack == NULL || needle == NULL)
{
return false;
}
const char* p;
if ((p = strstr(haystack, needle)) != NULL)
{
if (!strcmp(p, haystack + strlen(haystack) - strlen(needle)))
{
return true;
}
}
else
{
return false;
}
return false;
}
int main(int argc, char **argv)
{
FILE *file2 = fopen ("config.conf", "r");
const size_t line_size = 300;
char* line = malloc(line_size);
while (fgets(line, line_size, file2) != NULL) {
puts(line);
if (EndWith(line, "za"))
{
puts("it does.");
}
}
return 0;
}
my file config.conf :
vm.user_reserve_kbytes = 131072 za
vm.vfs_cache_pressure = 1001 za
vm.zone_reclaim_mode = 01 za