c - 如何使用 while 循环将文件的内容读入两个单独的字符缓冲区?
问题描述
首先,我试图在 C 中模拟“uniq”Linux 命令,只使用系统调用。我目前正在尝试做的是将文本文件中的行读入两个不同的字符缓冲区,即char *buffer1
和char *buffer2
.
这是我到目前为止所尝试的:
char *buffer1 = malloc(MAX_LINE_LENGTH * sizeof(char));
char *buffer2 = malloc(MAX_LINE_LENGTH * sizeof(char));
// read the first line into buffer1 using read() sys call
int i = 0;
while (read(input_fd, &buffer1[i], 1) == 1)
{
if (buffer1[i] == '\n')
{
buffer1[i] = '\0';
write(output_fd, buffer1, i);
break;
}
else
{
i++;
if (i > MAX_LINE_LENGTH)
{
perror("ERROR: Line is longer than the allocated buffer.\n");
exit(EXIT_FAILURE);
}
}
}
// read the second line into buffer2
int j = 0;
char *temp_ptr;
while(read(input_fd, &buffer2[j], 1) == 1)
{
if (buffer2[j] == '\n')
{
buffer2[j] = '\0';
while (buffer2 != NULL)
{
if (strcmp(buffer1, buffer2) != 0)
{
write(output_fd, buffer2, j);
}
j = 0;
// after this if-statement, read in another line of text and compare it
// to the string in buffer2
temp_ptr = buffer2;
if (temp_ptr == buffer2)
{
temp_ptr = buffer1;
}
else
{
temp_ptr = buffer2;
}
}
}
else
{
j++;
if (j > MAX_LINE_LENGTH)
{
perror("ERROR: Line is longer than the allocated buffer.\n");
exit(EXIT_FAILURE);
}
}
}
这可以只使用一个while循环来完成吗?再一次,我想强调一个事实,我只能使用系统调用。任何帮助是极大的赞赏!
解决方案
我想通了:
// read the first line into buffer1 using read() sys call
int i = 0;
while (read(input_fd, &buffer1[i], 1) != 0)
{
if (buffer1[i] == '\n')
{
buffer1[i] = '\0';
write(output_fd, buffer1, i);
i = 0;
break;
}
else
{
i++;
if (i > MAX_LINE_LENGTH)
{
perror("ERROR: Line is longer than the allocated buffer.\n");
exit(EXIT_FAILURE);
}
}
}
int j = 0;
ssize_t nr;
while (read(input_fd, &buffer2[j], 1) != 0)
{
if (buffer2[j] == '\n')
{
buffer2[j] = '\0';
if (strcmp(buffer1, buffer2) != 0)
{
write(output_fd, buffer2, j);
if (nr == -1) {
perror("ERROR.\n");
}
}
j = 0;
char *current_ptr = buffer2;
if (current_ptr == buffer2)
{
current_ptr = buffer1;
}
else
{
current_ptr = buffer2;
}
}
else
{
j++;
if (j > MAX_LINE_LENGTH)
{
perror("ERROR: Line is longer than the allocated buffer.\n");
exit(EXIT_FAILURE);
}
}
}
推荐阅读
- bash - 使用 ansible 在 Openstack 中运行服务器后运行 shell 命令
- javascript - 为什么我的选择菜单的占位符没有使用 jquery 设置 setAttribute 选择器?
- php - Laravel Eloquent 收集方法不存在
- python - 在python中用Qt实现一个取消按钮
- powershell - 集成 Octopus 和 powershell
- javascript - Node.JS/Passport-CI-OIDC - 错误:发送后无法设置标头。在 ServerResponse.OutgoingMessage.setHeader
- mysql - 不正确的整数值:列“user_id”的“未定义”
- google-apps-script - 如何将 Google 表格图表复制到 Google 文档
- python - BLENDER:将输出永久重定向到 Python 控制台
- sas - SAS EG Proc SQL - 将括号添加到 WHERE