struct DVDInfo *ReadStruct(void) {
struct DVDInfo *infoPtr;
int num;
char line[ kMaxLineLength ];
char *result;
infoPtr = malloc(sizeof(struct DVDInfo));
if (NULL == infoPtr) {
printf("Out of memory!!! Goodbye!\n");
exit(0);
}
printf("Enter DVD Title: ");
result = fgets(line, kMaxLineLength, stdin);
line[ strlen(line) - 1 ] = '\0';
infoPtr->title = MallocAndCopy(line);
printf("Enter DVD comment: ");
result = fgets(line, kMaxLineLength, stdin);
line[ strlen(line) - 1 ] = '\0';
infoPtr->comment = MallocAndCopy(line);
do {
printf("Enter DVD Rating (1-10): ");
scanf("%d", &num);
Flush();
}
while ((num < 1) || (num > 10));
infoPtr->rating = num;
printf("\n----------\n");
return(infoPtr);
}
Hice una pregunta diferente sobre este código en otro hilo en stackoverflow pero no quería doblarlo: ¿por qué se agrega el cero de finalización al final de estos archivos leídos por fgets? Fgets agrega el cero de finalización de todos modos, ¿no es esto exagerado?fgets naturalmente pone un cero de finalización en C?
C ha de desbordamiento del búfer suficientes oportunidades como es. Uno debería animar cuando las funciones se toman el tiempo para asegurar que una cadena termine correctamente. (Una cadena en C * debe * terminar con un NUL para ser una cadena válida, por definición en C.) –
Sí, es excesivo. –