How to make fwrite only write the character instead of the entire record?

Asked

Viewed 55 times

0

I’m making a code that reads a file with records of fixed size (storing in struct hist), and inserts them into another formatting file so that they have variable size. To indicate that the struct has already been inserted, I am writing * at the beginning of the record in the insertion file.

fread(&hist, sizeof(hist), 1, insereCopia);     // faz a leitura de insereCopia

while(hist.ID_aluno[0] == '*'){                 // verifica qual o próximo registro a ser inserido
    fread(&hist, sizeof(hist), 1, insereCopia);
    cont++;
}

fseek(insereCopia, cont * sizeof(hist), SEEK_SET);      // volta ao início do reg para definir o seu tamanho e indicar que ele já foi inserido

fwrite("*", sizeof(char), 1, insereCopia);

But instead of fwrite write only the character * it is always inserting the first record together in the insertion file. Any suggestions?

  • See: https://answall.com/help/minimal-reproducible-example here in my test the writing worked as expected.

1 answer

0

you can also use fputc(int character, FILE* file) for only one character

fputc('*',insereCopia);

*Obs: there is also the possibility that the last changes are not being saved due to a missing fclose(file) (to close the file)

*Obs2: an open file only as written, erases everything that was already in it before, and an arch only written with "append" ("w+"), will write only after everything that was already written at the time it was opened (fseek will not work for pointers before this point), so tbm do not use "append", in your case (fopen), the equivalent of "append" is the character '+'.

the result will probably be the same, I see no error in this part... probably, what you are seeing the most, are the previous data, opening a file as write and read simultaneously, your writings will overwrite byte by byte the existing data, example:

open a file, move the pointer to 5, write '*', what happens:

"text inside the file"

012345<pointer

exit:

"text*inside the file"

Different Approach, Abstraction

struct Hist {
    //variáveis...{
}
struct HistFile {
    FILE* file;
    HistFile(char* filepath) {//...abrir arquivo
    ~HistFile() {//...fechar arquivo
    int getCount() {
        fseek (file , 0 , SEEK_END);
        return ftell (pFile) / sizeof(Hist);
    }
    Hist get(int index) {
        fseek(file,index*sizeof(Hist),SEEK_SET);
        Hist ret;
        fread((const void*)&ret, sizeof(Hist), 1, file);
        return ret;
    }
    void set(Hist h, int index) {
        fseek(file,index*sizeof(Hist),SEEK_SET);
        fwrite((const void*)&h, sizeof(Hist, 1, file);
    }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.