【发布时间】:2021-04-01 20:06:54
【问题描述】:
我有两个缓冲区char *buffer1 和char *buffer2 使用malloc 在堆上分配。从文本文件中,我想将一行读入buffer1,将第二行读入buffer2,如何在同一个while循环下完成?
到目前为止,我已经弄清楚如何将第一行文本读入buffer1:
int i = 0;
while (read(input_fd, &buffer1[i], 1) == 1) {
// check if the line is longer than MAX_LINE_LENGTH
// otherwise, read the first line into buffer1
if (buffer1 > MAX_LINE_LENGTH) {
perror("Error: The line read in is longer than the allocated buffer.\n");
exit(EXIT_FAILURE);
} else {
// checking for end of line, then appending the null
// character to the right of the last read char in buffer1
// to indicate the line is over
if (buffer1[i] == '\n' || buffer1[i] == 0x0) {
buffer1[i] = '\0';
// write the first line in buffer1 to the terminal
write(output_fd, buffer1, strlen(buffer1));
}
}
}
【问题讨论】:
-
您可以使用指向缓冲区的指针,而不是直接使用缓冲区。你想只读取两行,还是读取任意数量的行并交替读取?
-
@Devolus 我想读取多行直到 EOF,同时交替使用 b/w buffer1 和 buffer2。例如,“这是第一句话”。将被读入 buffer1 和下一个相邻的句子,比如“这是下一个句子”。将被读入 buffer2 等等,直到 EOF。
-
"buffer1 > MAX_LINE_LENGTH" - 你是从哪里得到这个想法的?我想编译器警告过你。
标签: c file-io system-calls