Итак, я пытаюсь прочитать ввод из текстового файла и напечатать ту же самую вещь, которую я прочитал в C. Итак, ниже приведен ввод с последующим вводом:
ввод: Hi
вывод: Hi
#include <stdio.h>
#include <stdlib.h>
char *inputString(FILE *fp, size_t size) {
//The size is extended by the input with the value of the provisional
char *str;
int ch;
size_t len = 0;
str = realloc(NULL, sizeof(char) * size); //size is start size
if (!str)
return str;
while (EOF != (ch = fgetc(fp)) && ch != '\n') {
str[len++] = ch;
if (len == size) {
str = realloc(str, sizeof(char) * (size += 16));
if (!str)
return str;
}
}
str[len++] = '\0';
return realloc(str, sizeof(char) * len);
}
int main(void) {
char *m;
// printf("input string : ");
m = inputString(stdin, 10);
printf("%s\n", m);
free(m);
return 0;
}
Для этого ввода:
Hi, this is the first line
This is the second line
This is the third line \n
Это вывод, который я ожидал:
Hi, this is the first line
This is the second line
This is the third line \n
Вот что я получил:
Hi, this is the first line
Имеет смысл, что код печатает только первую строку, но так как условие в охране больше не будет истинным после нажатия новой строки, но я не знаю, как структурировать свой код такон читает построчно и печатает их соответственно.