c - 在 fprintf 中传递参数的问题

标签 c

warning: passing argument 2 of ‘fprintf’ from incompatible pointer type

warning: format not a string literal and no format arguments

stdio.h:333: note: expected ‘const char * restrict’ but argument is of type ‘struct FILE *’

#include <stdio.h>

    int main (void){
    FILE *file;
    unsigned char *buffer;
    unsigned long fileLen;

    //Open file
    file = fopen("squirrel-gray.jpg", "rb");
    if (!file)
    {
            fprintf(stderr, "Unable to open file %s", "squirrel_gray.jpg");
            return;
    }

    //Get file length
    fseek(file, 0, SEEK_END);
    fileLen=ftell(file);
    fseek(file, 0, SEEK_SET);

    //Allocate memory
    buffer=(char *)(fileLen);
    if (!buffer)
    {
            fprintf(stderr, "Memory error!");
                            fclose(file);
       }
    fclose(file);

    FILE *image;
    image = fopen("img.jpg", "w");
    fprintf(image, file);
    fclose(image);

}

最佳答案

行:

fprintf( image, file ) ;

fileFILE* 而不是格式字符串。编译器警告的含义与它所说的完全一样(并且是语义错误)。

大概您打算将buffer的内容写入img.jpg?原来如此:

  • 您尚未将任何数据读入缓冲区,
  • 您尚未为缓冲区分配任何内存,
  • 在任何情况下,格式化 I/O 都完全不适合写入二进制文件。

也许:

//Allocate memory
buffer = malloc( fileLen ) ;
if( buffer == NULL )
{
    fprintf( stderr, "Memory error!" ) ;
}
else
{
    // Read data from file
    fread( buffer, 1, fileLen, file ) ;

    // Write data to image (img.jpg)
    FILE* image = fopen( "img.jpg", "wb" ) ;
    if( image != NULL )
    {
        fwrite( buffer, 1, fileLen, image ) ;
        fclose( image ) ;
    }
}
fclose( file ) ;

关于c - 在 fprintf 中传递参数的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24044578/

相关文章:

c++ - emacs C/C++ 缩进 : different for pre and post comments//or: how can I make certain comments like//^ be indented extra?

c - 从字符中提取位序列

java - Java Interposer 中的堆栈粉碎

c - C 中的二叉树 - 多个数据

c - 这段代码有什么作用? C

c - C 的基本非阻塞 tcp 连接示例

c - C 中的定点无符号除法

c - 如何将一组属性应用于 Visual Studio 项目中的文件子集?

c - 在 C 中用 gets 读取一个 txt 文件

c - 如何用C写 "if x equals 5 or 4 or 78 or..."