E
E
Evgeny Yakushov2020-04-20 19:17:42
C++ / C#
Evgeny Yakushov, 2020-04-20 19:17:42

Why does a warning pop up, followed by a segmentation fault?

I write the structure to a file, I write each field separately, fields of the char type are written without errors, but uint8_t or an ordinary int cannot be written, a warning pops up at the compilation stage, and during operation there is already a segmentation error. What to do?
I write under Linux
Error in this line:

fwrite(structFile->fileCountBlocks, sizeof(uint8_t), 1, archiv);

The code:
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
#include <sys/stat.h>

#define SIZEBLOCK 256

struct File {
  char fileName[64];
  char fileContent[SIZEBLOCK];
  uint8_t fileCountBlocks;
};

void archivingFile(FILE *thisFile, char *name) {
  FILE *archiv = fopen("FileArchiv", "wb");
  if (archiv == NULL) {
    printf("Couldn't create file archive!\n");
    return;
  }
  
  struct File *structFile = malloc(sizeof(struct File));

  strcpy(structFile->fileName, name);

  fseek(thisFile, 0, SEEK_END);
  uint32_t size = ftell(thisFile);
  fseek(thisFile, 0, SEEK_SET);
  
  structFile->fileCountBlocks = size / SIZEBLOCK + 1;
  
  fwrite(structFile->fileName, sizeof(structFile->fileName), 1, archiv);
  for (uint8_t i = 0; i < structFile->fileCountBlocks; i++)
  {
    fread(structFile->fileContent, SIZEBLOCK, 1, thisFile);
    fwrite(structFile->fileContent, SIZEBLOCK, 1, archiv);
  }

  printf("[%i blocks][%u bytes] %s\n", structFile->fileCountBlocks, size, structFile->fileName);
  // Если убрать строку, то сегментирования не будет и отработает все как надо, НО мне нужна переменная
  fwrite(structFile->fileCountBlocks, sizeof(uint8_t), 1, archiv);

  free(structFile);
  fclose(archiv);
}

void preparationForArchiving() {
  char *name = NULL;
  printf("Enter folder or file name: ");
  scanf("%ms", &name);
  printf("\n");
  DIR	*dir	= opendir(name);

  if (dir == NULL) {
    FILE *file = fopen(name, "rb");
    if (file == NULL) {
      printf("Can't open folder or directory: %s\n", name);
      return;
    } else {
      archivingFile(file, name);
    }
  } else {
    //archivingDir();
  }
  free(name);
}

int main(void) {
  preparationForArchiving();
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
1
15432, 2020-04-20
@yevgenyyakushov

The fwrite function takes as input a pointer from which to take data. You palm off value of byte instead of the address. You need to pass a pointer to a variable:

fwrite(&structFile->fileCountBlocks, sizeof(uint8_t), 1, archiv);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question