Простой пример использования связанных имен для вашего списка:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct NameList {
char * name;
struct NameList * next;
} NameList;
int append(NameList ** head, NameList ** tail, char * s)
{
NameList * l;
if (((l = malloc(sizeof(NameList))) == NULL) ||
((l->name = strdup(s)) == NULL))
/* not enough memory */
return 0;
l->next = NULL;
if (*head == NULL) {
*head = *tail = l;
}
else {
(*tail)->next = l;
*tail = l;
}
return 1;
}
int main(void) {
char filename[25];
FILE * f;
printf("Enter the file name: ");
if (scanf("%24s", filename) != 1)
return 0;
f = fopen(filename, "r");
if (f == NULL)
{
puts("No file found.");
return 0;
}
NameList * head = NULL;
NameList * tail = NULL;
char s[64];
/* suppose a name has no space even composed and less than 64 characters */
while (fscanf(f, "%63s", s) == 1) {
if (!append(&head, &tail, s))
return 0;
}
fclose(f);
printf("The names in %s file are:\n", filename);
NameList * l;
l = head;
while (l != NULL) {
puts(l->name);
l = l->next;
}
/* search longer name */
size_t maxlen = 0;
char * longer = NULL;
l = head;
while (l != NULL) {
size_t ln = strlen(l->name);
if (ln > maxlen) {
maxlen = ln;
longer = l->name;
}
l = l->next;
}
if (longer != NULL)
printf("longer name is : %s\n", longer);
/* free resources */
while (head != NULL) {
l = head;
head = head->next;
free(l->name);
free(l);
}
return 0;
}
Компиляция и выполнение
pi@raspberrypi:/tmp $ gcc -pedantic -Wextra l.c
pi@raspberrypi:/tmp $ cat aze
firstname secondname
anothername
lastname
pi@raspberrypi:/tmp $ ./a.out
Enter the file name: aze
The names in aze file are:
firstname
secondname
anothername
lastname
longer name is : anothername
Выполнение в valgrind
pi@raspberrypi:/tmp $ valgrind ./a.out
==10132== Memcheck, a memory error detector
==10132== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==10132== Using Valgrind-3.13.0 and LibVEX; rerun with -h for copyright info
==10132== Command: ./a.out
==10132==
Enter the file name: aze
The names in aze file are:
firstname
secondname
anothername
lastname
longer name is : anothername
==10132==
==10132== HEAP SUMMARY:
==10132== in use at exit: 0 bytes in 0 blocks
==10132== total heap usage: 12 allocs, 12 frees, 6,570 bytes allocated
==10132==
==10132== All heap blocks were freed -- no leaks are possible
==10132==
==10132== For counts of detected and suppressed errors, rerun with: -v
==10132== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 6 from 3)
Обратите внимание, что связанный список можно заменить массивом char*
, используя realloc , чтобы увеличить его размер при чтении имен и т. Д.