C fwrite 字符数组

问题描述

这是一个函数,使用一组预定义的代码将输入文件(infp)编码为输出文件(outfp)(在普通文本模式下)

void encode( char *codes[],FILE *infp,FILE *outfp) {
    while (infp) {
        if (feof(infp)) {
            break;
        }
        char buffer[256];
        sprintf(buffer,"%s",codes[fgetc(infp)]);
        printf("%lu,%s\n",strlen(buffer),buffer); //this works
        fwrite(buffer,sizeof(char),outfp);
    }
};

codes 是一个长度为 256 的字符数组
例如codes[65]返回ascii char A
代码 但是每个ascii字符的代码长度不同,最大为256

printf 行工作得很好,我得到了类似的东西:

6,100110
5,00000
4,0010
3,110
5,01011
4,0001

所以我希望输出的文本文件将是 100110000000010110010110001
但我对 fwrite 行一无所获,即输出文本文件为空白,
直到我将第三个参数放入 256,即

fwrite(buffer,256,outfp);

输出坚持有很多空和奇怪的字符

enter image description here

请帮忙。提前致谢!

解决方法

见feof()的定义[feof()参考][1] [1]:https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/feof

"例如,如果一个文件包含 10 个字节,而您从中读取了 10 个字节 文件,feof 将返回 0,因为即使文件指针是 在文件的末尾,您还没有尝试在末尾阅读。 只有在您尝试读取第 11 个字节后,feof 才会返回非零值 价值。”

while 不会停止(顺便说一句,这是无用的条件),并且 feof() 直到为时已晚才返回 1,您从 fgetc() 获得 -1,并将其用作数组中的索引,可能得到异常,程序在关闭输出文件前崩溃。

if (!infp || !outfp) {
    // Check that files opened successfully
    return;
}

while (true) {
    int index = fgetc(infp);
    if (index < 0) {
        // fgetc() return -1 on end of file
        break;
    }
    char buffer[256];
    sprintf(buffer,"%s",codes[index]);
    printf("%lu,%s\n",strlen(buffer),buffer); //this works
    fwrite(buffer,sizeof(char),outfp);
}
...
// Output file must be closed,otherwise it will be empty
fclose(outfp);