分段错误:11,代码适用于Windows但不适用于mac

时间:2018-03-22 21:48:40

标签: c

此函数应打印出名为filename的文件中字节的文本表示。它适用于Windows,但会出现分段错误:在Mac上有11个,感谢您的帮助

int hexdump(FILE *streaminput, FILE *streamoutput)
{   
unsigned char buffer[8];
int bytescount;
int n = 0;
streaminput=fopen(filename, "rb");//read binary file
setvbuf(streaminput,NULL,_IOFBF,1024);//Buffer size to 1024 bytes
if(streaminput==0)
{
    printf("cannot open file");
    return 0;
}
for (;;)//read to the end of file,end feof(stream)!=0//
{   
    bytescount=fread(buffer,1,8,streaminput);//fread(void *buffer, 
size_t size, size_t count, FILE * stream)//
    //dec2hex(n, buf);//
    if (bytescount==0)
    {
        fprintf(streamoutput,"%07X",n);
        break;
    }
    fprintf(streamoutput,"%07X",n);

    for(int i=0;i<bytescount;i++)
    {
        if(((char)buffer[i] >= 32) && ((char)buffer[i] <= 126))
        {
            //fprintf(streamoutput,"  %02x%c ",buffer[i],buffer[i]);
            printf(" %02X %c ",buffer[i],buffer[i]);
            //printf("%c",isprint(buffer[i]),buffer[i]);//
        }   
        else
        {
        printf(" %02X . ",buffer[i],buffer[i]);
        }
    }
    printf("\n");
    n = n+bytescount;
    if (bytescount <8)
    {
        fprintf(streamoutput,"%07X",n);
        break;
    }


}
fclose(streaminput);
streaminput=NULL;
return 0;
}

1 个答案:

答案 0 :(得分:0)

我猜您的问题是路径,您在Windows中提供的路径就像

C:\Users\Name\b.txt

但在linux和mac中就像是

/home/name/b.txt

建议使用相对路径并使用文件分隔符

inline char separator()
{
#ifdef _WIN32
    return '\\';
#else
    return '/';
#endif
}