繁体   English   中英

如何在AC程序中从命令行打开和读取二进制文件

[英]How to open and read binary files from command line in a c program

我正在尝试用C语言编写代码以使用Linux从命令行读取二进制文件。 读取文件的规格如下:

*输入文件的名称将作为命令行参数传递到程序中。

*程序将打开此二进制文件并读取文件中的第一个整数。 然后,它将使用malloc函数动态创建此大小的浮点数组。

*然后程序将读取浮点值并将它们存储到此新创建的数组中。

我唯一能成功做的就是打开文件。我以前尝试通过执行以下操作分配一块内存

file=double*malloc(30*sizeof(double));

但是尝试将文件放在fread功能的* ptr参数中时,我一直遇到错误并遇到一些严重的问题

 size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);

这是我到目前为止的内容:

#include <stdio.h>

int main ( int argc, char *argv[] )
{
    if ( argc != 2 ) 
    {

        printf( "usage: %s filename", argv[0] );
    }
    else 
    {

        FILE *file = fopen( argv[1], "r" );


        if ( file == 0 )
        {
            printf( "Could not open file\n" );
        }
        else 
        {
            int x;

            while  ( ( x = fgetc( file ) ) != EOF )
            {
                printf( "%c", x );
            }
            fclose( file );
        }
    }
}

也许是这样的吗?

    int size;
    float *floatArray;
    FILE *file = fopen( argv[1], "r" );

    fread(&size, sizeof(int), 1, file);
    floatArray = (float*) malloc(sizeof(float) * size);
    fread(floatArray, sizeof(float), size, file);

    for(int i = 0; i < size; i++)
    {
        printf("%d: %f\n", i+1, floatArray[i]);
    }
#include <stdio.h>
#include <stdlib.h> /* for malloc() and exit() function */

int main(int argc, char* argv[])
{
    FILE *file;
    int i, n; /*  the counter and num of floating point numbers */
    float* val; /* pointer for storing the floating point values */
    if(argc<2)
    {
        printf( "usage: %s filename", argv[0] );
        exit(-1);
    }
    if((file = fopen( argv[1], "rb" )) ==NULL)
    {
        printf( "Could not open file.\n" );
        exit(-2);
    }
    if(fread(&n, sizeof(int), 1, file)!=1)
    {
        printf( "Could not read data from file.\n" );
        exit(-3);
    };

    if((val = malloc(n*sizeof(float)))==NULL)
    {
        printf( "Could not allocate memory for data.\n" );
        exit(-4);
    };
    printf("Number of data values: %d\n", n);
    if(fread(val, sizeof(float), n, file)!=n) /* read each floating point value one by one */
    {
        printf( "Could not read data from file.\n" );
        exit(-5);
    }
    for(i=0; i<n; ++i)
    {
        printf("%f \t", val[i]); /* now print it */
    }
    free(val); /* free the allocated memory */
    fclose(file); /* close the file */
    return 0;
}

注意:

  1. 假定int的大小与数据文件中的大小相同,并且shortlong或其他任何形式。
  2. 另外,假定数据文件字节序与运行上述代码的计算机字节序 相同

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM