c - C - 写入文件的字符出现次数
问题描述
我正在编写一个编码函数,它从源文件中获取文件描述符,并将 FILE* 作为目标文件。如果输入文件有这个:AABBBcccc
那么我应该写2A3B4c
在输出文件中。(相同连续字符的编号)。我设法做到了这一点,但我唯一的问题是第一个字母的出现次数得到了 +1 ......所以我会得到 : 3A3B4c
。该函数返回在 outt 中写入的字符总数。
int encode_aux(int fd1, char *buffer, FILE *outt)
{
size_t c = read(fd1, buffer, sizeof(buffer) - 1);
char previous; //to check if the next character is the same
int count = 0; //number of occurence of the same character
int total = 0; //total number of chars written in the output file
while (c != 0)
{
for (size_t i = 0; i < c; i++)
{
if (count == 0)
{
previous = buffer[i];
count += 1;
}
if (count != 0)
{
if (previous == buffer[i])
{
count += 1;
}
else
{
if (i == 0)
{
count -= 1;
}
if (count != 1)
{
total += fprintf(outt, "%d", count);
}
total += fprintf(outt, "%c", previous);
previous = buffer[i];
count = 1;
}
}
}
buffer[c] = '\0';
c = read(fd1, buffer, sizeof(buffer) - 1);
}
return total;
}
int encode(const char *file_in, const char *file_out)
{
FILE *out = fopen(file_out, "w");
char buff[4096];
int fd = open(file_in, O_RDONLY);
if (fd == -1 || out == NULL)
{
return -1;
}
int tot = encode_aux(fd, buff, out);
if (close(fd) == -1 || fclose(out) != 0)
{
return -1;
}
return tot;
}
解决方案
if (count == 0)
{
previous = buffer[i];
count += 1;
}
if (count != 0)
{
if (previous == buffer[i])
{
count += 1;
}
那时。count == 0
_ count = 1
然后你检查count != 0
,因为你刚刚做了count += 1
,因为count
是 0。然后if (previous == buffer[i])
,这也将永远是真的,因为你只是先做了previous = buffer[i]
int he if。然后你再次增加计数。
我想你错过了一个其他的:
if (count == 0)
{
previous = buffer[i];
count += 1;
} else
if (count != 0)
{
if (previous == buffer[i])
{
count += 1;
}
笔记:
- 我认为您正在
fgets
与read
电话混在一起。buffer[c] = '\0';
不需要,调用read
只是从文件描述符中读取字节,无论它们是什么,如果c
对 来说太错误buffer
,它将是越界访问。 - 您没有打印文件最后一个字符的计数。碰巧的是,您的文件以换行符结尾 -
previous
在最后一次执行循环时设置为换行符。如果您的文件不以 w 换行符结尾,则不会打印最后一个字符的计数。
推荐阅读
- c# - 如何从文本字符串创建 .tar.gz 文件
- reactjs - 如何在反应js中删除jspdf pdf的空格
- python - 为什么 Numpy 矩阵在分配时会忽略 demicals?
- azure - R 的 Azuremlsdk 在解决环境时挂起更新
- reactjs - 如何在点击功能上执行以在反应中显示来自搜索栏的过滤结果
- python - 包含模板标签和表单的渲染问题
- java - Spring SOAP WS:实现 SimplePasswordValidationCallbackHandler 的 WssSoapFaultException
- regex - 用于查找多行的正则表达式
- terraform - 在 minikube 上使用带有 helm 的 terraform 会出错
- mongodb - 嵌入文档中的 Strapi mongodb 项目特定字段