Я написал это, но это не сработало: У меня есть файл с именем contact.txt, у меня есть текст, как я могу найти текст в файле, и если он совпадает, я должен распечатать этот текст в c
#include <stdio.h>
#include <stdlib.h>
#include <strings.h>
int main()
{
char don[150];
int tr,y;
FILE *efiom;
//this is the input of don blah blah blah
printf("Enter a search term:\n");
scanf("%s",&don);
//this is for the reading of the file
efiom =fopen("efiom.txt","r");
char go[500];
//OMO i don't know what is happeing is this my code
while(!feof(efiom))
{
// this is the solution for the array stuff
void *reader = go;
tr = strcmp(don,reader);
fgets(go, 500 ,efiom);
}
// my if statement
if (tr == 0)
{
printf("true\n");
}
else
{
printf("false\n");
}
fclose(efiom);
return 0;
}
Также fgets сохраняет любую завершающую новую строку, поэтому вы не получите совпадения строк. См. Удаление завершающего символа новой строки из ввода fgets().





Просто используйте эту функцию из string.h:
char * strstr (char * str1, const char * str2 );
Returns a pointer to the first occurrence of str2 in str1, or a null pointer if str2 is not part of str1.
The matching process does not include the terminating null-characters, but it stops there.
Прочитать файл в одну строку (char*). Вы можете использовать это:
FILE* fh = fopen(filename, "r");
char* result = NULL;
if (fh != NULL) {
size_t size = 1;
while (getc(fh) != EOF) {
size++;
}
result = (char*) malloc(sizeof(char) * size);
fseek(fh, 0, SEEK_SET); //Reset file pointer to begin
for (size_t i = 0; i < size - 1; i++) {
result[i] = (char) getc(fh);
}
result[size - 1] = '\0';
fclose(fh);
}
Помните о free(result);, когда вы выполняли операции с этим.
Как "не получилось"? Примечание: см. Почему
while ( !feof (file) )всегда неправильно? Лучше какwhile(fgets(go, 500 ,efiom) != NULL) { /*...*/ };