【发布时间】:2020-02-16 03:40:38
【问题描述】:
我正在编写一个编码函数,它从源文件中获取文件描述符,并将 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;
}
【问题讨论】:
-
sizeof(buffer) - 1是sizeof(char *) - 1- 它是指向 char 的指针的大小减 1。the same所以你在做char buffer [sizeof(char*) - 1]; encode(..., buffer, ...)? -
我不想得到“\n”。我添加了调用函数
-
你做了
char buff[4096];。sizeof(buffer)内部encode_aux是指针的大小,而不是缓冲区指针后面的内存大小 -sizeof(char*)例如,在 32 位计算机上是4,或者在 64 位计算机上是8。因此,您不是一次读取 4095 个字符 - 例如,您正在读取 3 或 7 个字符,具体取决于您的架构。I don't want to get the "\n"-read不解析数据,你可以手动忽略if (buffer[i] == '\n') continue;不想解析的数据,例如使用isspacefromctype.h
标签: c string file encoding char