C程序忽略if​​语句包含sizeof

you*_*his -1 c if-statement file sizeof

我目前正在编写一个简单的小型一次性垫程序.我希望它在keyfile小于source文件时警告用户,但是当我运行它时我的程序只是忽略它.

/* Check if keyfile is the same size as, or bigger than the sourcefile */
if(sizeof keyfile < sizeof sourcefile)
{
printf("Source file is larger than keyfile.\n");
printf("This significantly reduces cryptographic strength.\n");
printf("Do you wish to continue? (Y/N)\n");
scanf("%c", &ans);
if(ans == 'n' || ans == 'N')
    {
    return (1);
    }
if(ans == 'y' || ans == 'Y')
    {
    printf("Proceeding with Encryption/Decryption.\n");
    }
Run Code Online (Sandbox Code Playgroud)

我怀疑问题在于我的使用sizeof,但我不知道其他任何选择?有关如何更改我的代码以使其工作的任何建议?

编辑:我已尽力增加fstat我的能力,但它仍然以同样的方式作出反应......这就是我所做的:

/* Get size of sourcefile. */
if((sourcefile = fopen(argv[1], "rb"))== NULL)
{
printf("Can't open source file.\n");
printf("Please enter a valid filename.\n");
printf("USAGE: OTP <source file> <output file> <keyfile>\n");
return (1);
}

fflush(sourcefile);
fstat(fileno(sourcefile), &statbuf);
fclose(sourcefile);

/* Get size of keyfile. */
if((keyfile = fopen(argv[3], "rb"))== NULL)
{
printf("Can't open keyfile.\n");
printf("Please enter a valid filename.\n"); 
printf("USAGE: OTP <source file> <output file> <keyfile>\n");
return(1);

fflush(keyfile);
fstat(fileno(keyfile), &keybuf);
fclose(keyfile);
}
Run Code Online (Sandbox Code Playgroud)

并修改了被忽略的if语句的第一行:

if((keybuf.st_size) < (statbuf.st_size))
Run Code Online (Sandbox Code Playgroud)

为什么它仍然被程序忽略?

tom*_*ahh 10

sizeof不返回文件的大小.sizeof用于检查类型在内存中占用的字节数.

如果您想了解有关获取文件大小的更多信息,请查看帖子.


Dev*_*lar 5

sizeof是一个编译时运算符,以字节为单位产生其操作数的数据类型的大小.你确定这就是你想要做的吗?我非常怀疑,因为它似乎想要比较文件大小.(fopen(),fseek()结束,ftell()获取文件的大小,或者操作系统'API为您提供的更舒适的功能.)