1
如何使用malloc逐行打印文件?理想情況下,我想分配足夠的空間在文件中保留一行,打印它,釋放它,然後重複該過程。如何通過使用動態內存分配逐行打印文件?
請包括代碼片斷,謝謝!
這是我迄今爲止,但Valgrind說我有內存泄漏。
int main (int argc, char **argv)
{
// char *line = NULL;
char *line;
FILE *fp = fopen(argv[1], "r");
if (!fp) {
fprintf (stderr, "error: file open failed '%s'.\n", argv[1]);
return 1;
}
line = malloc(1);
while (readline(fp, line)) {
// printf("%s\n", line);
}
free(line);
if (fp != stdin) fclose (fp);
return 0;
}
char *readline (FILE *fp, char *buffer)
{
char ch;
int place = 0;
size_t nchar = 1;
ch = fgetc(fp);
while (ch != '\n' && ch != EOF)
{
nchar++;
(buffer)[place] = ch;
char *tmp = realloc (buffer, nchar);
if (!tmp) {
fprintf (stderr, "error: realloc failed, "
"returning partial buffer.\n");
(buffer)[place] = 0;
return buffer;
}
buffer = tmp;
ch = fgetc(fp);
place++;
}
(buffer)[place] = '\0'; /* nul-terminate */
if (ch == EOF) {
if (strlen(buffer) > 1) {
printf("%s\n", buffer);
}
// free(buffer);
buffer = NULL;
} else {
if (strlen(buffer) > 1) {
printf("%s\n", buffer);
}
}
return buffer;
}
您是否嘗試過什麼了嗎?如果是這樣,你失敗了什麼?如果他們看到一些努力,人們會更願意提供幫助。 – HolyBlackCat
這是一個家庭作業,指示以某種方式做事嗎?如果沒有,「逐行打印」和「直到你看到它打印每個字符」之間有什麼區別,直到EOF。由於「\ n」是一個字符,因此它在某種意義上也會打印*行*,並且不需要任何內存分配。 – Telemachus
'malloc()'不打印。你打算怎麼讀線條? ['fgets()'](http://pubs.opengroup.org/onlinepubs/9699919799/functions/fgets.html), ['getline()'](http://pubs.opengroup.org/onlinepubs/ 9699919799/functions/getline.html),別的?你是否擔心來自終端(或FIFO或管道或其他非磁盤文件源)的信息? –