c - 在c中将数据从文件加载到数组

标签 c arrays file load save

我想从之前保存的文件中加载数组。我运行了下面的代码,但是由于某种原因,当我加载数组时,我加载的数组长度与我保存的数组的长度不同。如何更改加载文件代码的长度,以便它适用于任何数组长度?

intarr_t* intarr_load_binary( const char* filename )
{
    unsigned int len = 0;
    FILE *f = fopen (filename, "rb");
    fscanf (f, "%d", len);
    intarr_t* newia = malloc (sizeof(intarr_t));
    assert (newia);
    newia->data = malloc (len*sizeof(int));
    assert(newia->data);
    newia->len = len;
    if (f != NULL)
    {
        while (!feof(f))
        {
            fscanf (f, "%d", newia->data);
        }
    }
    else
    {
        return NULL;
    }
    fclose (f);
    return newia;
}

我用于保存/加载的结构在这里:

typedef struct {
  int* data;
  unsigned int len;
} intarr_t;

我用来保存文件的代码在这里:

int intarr_save_binary( intarr_t* ia, const char* filename )
{
    unsigned int len = ia->len;
    FILE *f;
    f = fopen (filename, "wb");
    if (fwrite (ia->data, sizeof(int), len, f) == len)
    {
        return 0;
    }
    else
    {
        return 1;
    }
    fclose (f);
}

最佳答案

the code is writing no length (len) value as the first data item to the file
yet the code is reading a length (len) value 
as if it were the first data item in the file.

this code is full of errors and oversights:

int intarr_save_binary( intarr_t* ia, const char* filename )
{
    unsigned int len = ia->len;
    FILE *f;
    f = fopen (filename, "wb");
    if (fwrite (ia->data, sizeof(int), len, f) == len)
    {
        return 0;
    }
    else
    {
        return 1;
    }
    fclose (f);
}

suggest using code similar to this:

int intarr_save_binary( intarr_t* ia, const char* filename )
{
    int returnValue = 0;
    unsigned int len = ia->len;
    FILE *f;

    if( NULL == (f = fopen (filename, "wb") )
    {
        perror( "fopen failed" );
        returnValue = 1;
    }

    else if ( fwrite ( &len, sizeof(int), 1, f) == 1 )
    { // then write of length successful

        if (fwrite (ia->data, sizeof(int), len, f) == len)
        {
            returnValue = 0; // indicate success
        }

        else
        { // else, write of data failed
            returnValue = 3;
        }
    }
    else
    { // else, failed to write len value to file
        returnValue = 4;
    }

    fclose( f ); // cleanup (writes last buffer to file)
    return( returnValue );
} // end function: intarr_save_binary

关于c - 在c中将数据从文件加载到数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27155585/

相关文章:

c - 自动输出一堆文件,以参数命名

对象的javascript数组推送值

javascript - 将对象内的多个数组合并为单个数组

java - 生成 null(从文件中读取一个单词)

c - 使用 strcmp 搜索相等的字符串

像 printf 一样连接一个字符串

arrays - 将大数组拆分为两个元素的数组

python - 文件对象对比文件名

file - 打印文件中一行的最后一列

c - 如何用 C 语言编写编译器?