Search code examples
cfilefopenfwrite

File returns garbage, but writes correctly


I'm writing a struct into a file, but it returns garbage. Here is my code:

ptFile = fopen("funcionarios.dat", "ab+");
fwrite(&novoFunc, sizeof(strFunc), 1, ptFile);

The values of struct novoFunc, before and after the fwrite are not garbage. However, when I return the file values:

ptFile = fopen("funcionarios.dat", "rb+");
[...]

fseek(ptFile, i*sizeof(strFunc), SEEK_SET); //on the loop, i goes from 0 to total structs
fread(&funcionario, sizeof(strFunc), 1, ptFile);

printf("Code: %d; Name: %s; Address: %s; CPF: %d; Sales: %d\n", funcionario.codigo, funcionario.nome, funcionario.endereco, funcionario.cpf, funcionario.numVendas);

Any idea why? The code was working fine, and I dont remember doing significative changes.

Thanks in advance

Edit: Struct definition

typedef struct func{

    int codigo;
    char nome[50];
    char endereco[100];
    int cpf;
    int numVendas;
    int ativo;


} strFunc;

Edit2: It just got weirder: it works fine on linux (using netbeans and gcc compiler), but it doesnt on windows (devcpp and codeblocks). Well, the entire code is here:

http://pastebin.com/XjDzAQCx

the function cadastraFucionario() register the user, and when I use listaFuncionarios(), to list all the registered data, it returns the garbage. Here is a print of what listaFuncionarios() returns:

http://img715.imageshack.us/img715/3002/asodfadhf.jpg

Im sorry the code isnt in english


Solution

  • This:

    it works fine on linux ... but it doesnt on windows

    is a big red flag. Windows has "text" files which are different to "binary" files. On Linux and other Unixes, there is no difference.

    Two lines in your source stand out:

    fopen("funcionarios.dat", "rb+");
    

    and later

    fopen("funcionarios.dat", "r+");
    

    That is, sometimes you open the file in "binary" mode, and sometimes in "text" mode. Make sure you always open any file in "binary" mode (that is, with the b in the mode string) if you ever intend to read or write non-text data.