Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

291
Visualizações
Writting zeros in file segment

I'm using fwrite to write a file (it's an image).

First, I'm writing a header that has a fixed size

int num_meta_write_bytes = fwrite(headerBuffer, 1, headerSize, file);

This works OK

Then I have to write the pixels:

num_write_bytes = fwrite(data_pointer, 1, image_size, file);

This works OK

For my case, I have to write a variable number of zeros between the header and the pixels, the (ugly?) solution I found is:

for (size_t i = 0; i < padding_zeros; i++) //padding_zeros is calculated in runtime
{
    uint8_t zero = 0;
    num_meta_write_bytes += fwrite(&zero, 1, sizeof(uint8_t), fp);
}

(This code is placed before writing the pixels)

My question is: is there a way to directly tell fwrite to continously write the same value padding_zeros times? instead of using this for loop?

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

You can create a zero-filled block of data with calloc(), then write that data to the file in one call (and remember to free the data afterwards):

uint8_t* zeros = calloc(padding_zeros, sizeof(uint8_t));
if (zeros) {
    num_meta_write_bytes += fwrite(zeros, sizeof(uint8_t), padding_zeros, fp);
    free(zeros);
}
else {
    // Error handling, or use your 'loop' method if calloc fails
}

As mentioned in the comments, you could also use a variable length array; however, VLAs are an 'optional' feature in C (since the C11 Standard), and you would anyway have to explicitly set the data to zeros (with a call to memset), as VLAs cannot be initialized like ordinary (fixed-size) arrays.

over 4 years ago · Santiago Trujillo Relatório

0

I found another solution, althouht I think is OS dependent:

fseek(fp, padding_zeros, SEEK_CUR);

This is quite fast as there is no allocation. Just when copying the resulting file, the OS will generate the actual zeros.

This worked fine in my linux target.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda