写入二进制文件(结构)

时间:2019-04-09 12:58:47

标签: c file binary structure

我使用fwrite来逐个写入结构的元素,但我不明白为什么在二进制文件中,除了仅来​​自结构的信息之外,还保存了更多的信息(不同的目录路径)?我仅采用在二进制文件中写入的方式。我也尝试在新的文本文件中写入相同的结构,并且在二进制文件中没有这样的问题。

struct student{
  int ID;
  char name[30];
  char secondName[30];
  double mark;
}typedef student;


int main()
{
  FILE *fp;

  struct student *student;
  int numberOfStudents;
  char *filename;
  int numberOfcharacter;

  student = (struct student *) malloc(numberOfStudents * sizeof(struct 
                                student));


  printf("Enter the number of character of the filename: ");
  scanf("%d", &numberOfcharacter);

  filename = (char *) malloc(numberOfcharacter * sizeof(char));

  if(filename == NULL)
    {
      perror("Memory error! ");
      exit(23);
    }

  fflush(stdin);

  printf("Write the name of your bin file: ");
  scanf("%s", filename);

  if((fp = fopen(filename, "wb")) == NULL)
    {
      perror("Error in creating the file! ");
      exit(2);
    }

  for(int i=0; i<numberOfStudents; i++) {

    int lenOfName = strlen((student+i)->name);
    int lenOfSecondName = strlen((student+i)->secondName);

    if(fwrite(&(student+i)->ID, sizeof(struct student), 1, fp) != 1)
      {
    perror("Error in writing! ");
    break;
      }

    if(fwrite(&lenOfName, sizeof(int), 1, fp) != 1)
      {
    perror("Error in writing! ");
    break;
      }

    if(fwrite((student+i)->name, sizeof(struct student), lenOfName, fp) 
       != lenOfName)
      {
    perror("Error in writing! ");
    break;
      }

    if(fwrite(&lenOfSecondName, sizeof(int), 1, fp) != 1)
      {
    perror("Error in writing! ");
    break;
      }

    if(fwrite((student+i)->secondName, sizeof(struct student), 
          lenOfSecondName, fp) != lenOfSecondName)
      {
    perror("Error in writing! ");
    break;
      }

    if(fwrite(&(student+i)->mark, sizeof(struct student), 1, fp) != 1)
      {
    perror("Error in writing! ");
    break;
      }

  }

  free(filename);
  free(student);
  fclose(fp);

0 个答案:

没有答案