从二进制文件中逐行打印序列

问题描述 投票:0回答:1

从二进制文件中读取。我被要求找出超过4个字符的序列,并且每行打印出一个序列。 check是一个检查字符是否可打印的功能。但是我的程序不断在序列之间打印出一条完整的新行,有时它会打印出只有3个字符长的序列。 size是文件大小,start和end表示序列的第一个字符的索引和最后一个字符的索引。以下是我的代码的一部分:

char* buffer = malloc(size);
fread(buffer, size, 1, file);   
while (end + 1 <= size){
    while(check(buffer[end]) == 1){
        end++;
    }
    if ((end - start + 1 ) >= 4){
        printf("%.*s\n", end - start + 1, &buffer[start]);
    }
    end++;
    start = end;
}
free(buffer);
fclose(file);

int check(char char){
if ((char >= 32)&&(char <= 126))
    return 1;
else
    return 0;
}
c file malloc
1个回答
0
投票

您正在使用像printf("%20s")这样的东西,它希望以0结尾的字符串作为输入。请注意,fread不会添加这样的终止字符;此外,20表示最小宽度和填充,但printf永远不会截断值。因此,它将打印直到输入字符串的(可能缺少的)结尾,可能超过缓冲区并产生未定义的行为。

我会做以下事情:

char* buffer = malloc(size+1);
fread(buffer, size, 1, file);
buffer[size]='\0';  // to be sure that you come to an end

while (end + 1 <= size){
    while(check(buffer[end]) == 1){
        end++;
    }
    if ((end - start + 1 ) >= 4){
        buffer[end] = '\0'; // terminate the sequence
        printf("%s\n", &buffer[start]);
    }
    end++;
    start = end;
}
free(buffer);
fclose(file);
© www.soinside.com 2019 - 2024. All rights reserved.