簡體   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