在C中有文件的麻烦

时间:2018-11-21 00:53:59

标签: c file

我正在尝试编写函数来帮助我保存和加载文件...但是当我尝试从文件中保存数组时,它与我加载到文件中的原始数组不匹配。这是我的代码。

#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <string.h>

#include "intarr.h"

/* LAB 6 TASK 1 */

/*
  Save the entire array ia into a file called 'filename' in a binary
  file format that can be loaded by intarr_load_binary(). Returns
  zero on success, or a non-zero error code on failure. Arrays of
  length 0 should produce an output file containing an empty array.
*/

int intarr_save_binary( intarr_t* ia, const char* filename )
{
  FILE* f = fopen( "filename", "wb" );

  if( f == NULL )
  {
    return 1;
  }

  if( fwrite( &ia->len, sizeof( int ), 1, f ) != 1 )
  {
    return 1;
  }

  if( fwrite( &ia->data, sizeof( int ), ia->len, f ) != ia->len )
  {
    return 1;
  }

  fclose( f );

  return 0;
}

/*
  Load a new array from the file called 'filename', that was
  previously saved using intarr_save_binary(). Returns a pointer to a
  newly-allocated intarr_t on success, or NULL on failure.
*/

intarr_t* intarr_load_binary( const char* filename )
{
  if( filename == NULL )
  {
    return NULL;
  }

  FILE* f = fopen( "filename", "rb" );

  if( f == NULL )
  {
    return NULL;
  }

  int len;

  if( fread( &len, sizeof( int ), 1, f ) != 1 )
  {
    return NULL;
  }

  intarr_t* new_ia = intarr_create( len );

  fread( new_ia->data, sizeof( int ), len, f );

  fclose( f );

  return new_ia;
}

也要清楚intarr_t ia只是具有ia-> data(数组)和ia-> len(数组的len)的结构

1 个答案:

答案 0 :(得分:1)

在此行中,您正在编写指针的内容,而不是指针指向的数据。如果长度足够,您可能会写入其他随机数据,并遵循未定义行为

fwrite( &ia->data, sizeof( int ), ia->len, f )

问题是您通过获取ia->data的地址来增加了一层重定向。好像您只是有复制粘贴错误之类。删除&

fwrite( ia->data, sizeof( int ), ia->len, f )